javascript - jQuery、Ajax : Unable to replace HTML

标签 javascript jquery ajax

网页上有一个按钮。单击时,它将用标题( <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>

ma​​in.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);ma​​in.js

如果我替换data"displayText" ,它将替换元素 index.htmldisplayText

如果我从目录中删除 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/

相关文章:

javascript - Three.js - 围绕特定 Axis 旋转球体

javascript - 用户输入的 javascript 不如浏览器 Web 开发人员工具安全?

javascript - 如何在nodejs中同时运行两个promise并一一失败

javascript - 内容隐藏在导航栏中 - 一页网站

javascript - 使用Ajax调用表数据中的php文件出错

javascript - 适用于发布商的 DoubleClick : Specify browser and ad dimensions

javascript - 在 Javascript 中处理浏览器的 HTTP 请求超时

jquery - 父菜单下的位置子菜单在 IE/FF 中不起作用

javascript - AJAX 错误状态代码 500 内部服务器错误

java - 无法获取 Ajax 响应中的值