[英]jQuery, Ajax: Unable to replace HTML
網頁上有一個按鈕。 單擊時,它將用標題( <h1>
)替換段落( <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");
}
});
});
$(document).ready(function(){
$('#myButton').click(function(){
$.get("Info.html", function (data, status){
if (status ==="success"){
$('#replaceableP1').html(data);
} else {
$("#replaceableP1").html("Problem reading data");
}
});
});
});
試試這個,檢查是否加載了js文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.