网页上有一个按钮。单击时,它将用标题( <p>
)替换段落( <h1>
)。
但是,我似乎无法让它发挥作用:
index.html
<head>
<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
<script src="js/libs/jquery/jquery.js"></script>
<script src="js/libs/jqueryui/jquery-ui.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<section>
<p id="replaceableP1">This text will be replaced </p>
<button id="myButton">Get External Data</button>
</section>
</body>
main.js
$(document).ready(function(){
$("#myButton").click(function(){
$.get("someInfo.html", function (data, status){
if (status === "success"){
$('#replaceableP1').html(data);
} else {
$("#replaceableP1").html("Problem reading data");
}
});
});
});
someInfo.html
<h1>This is external data!</h1>
错误生成于:$('#replaceableP1').html(data);
在 main.js
如果我替换data
与 "displayText"
,它将替换元素 index.html 和 displayText。
如果我从目录中删除 someInfo.html,网页甚至不会生成错误消息:读取数据时出现问题。
代码有什么问题吗?
编辑:我的错,我忘了有 $("#myButton").click(function(){
最佳答案
我看到了两件事。首先是你有一个额外的“});”在你的 main.js 文件中。第二个是 .html 将替换所选元素的内部 HTML。如果你想更换<p>
与 <h1>
,您将使用 .replaceWith。
例如,
$(document).ready(function() {
$.get("someInfo.html", function(data, status) {
if (status === "success") {
$('#replaceableP1').replaceWith(data);
} else {
$("#replaceableP1").html("Problem reading data");
}
});
});
关于javascript - jQuery、Ajax : Unable to replace HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37119422/