javascript - text() 与 .parent().html() 后续更改的 JQuery 行为

标签 javascript jquery html

我的代码中有一个场景,之前每次单击按钮时我都会使用 element.text(data) 更新 div。

我已经更新了这个,因为我现在需要将 html 而不是文本传递到 div 中。因此,现在的调用是 element.parent().html(data)。

第一次单击按钮时它可以正常工作,但似乎有意想不到的副作用,现在只允许我更新一次。为了确定起见,我将其改回 .text() ,果然我能够多次单击不同内容的按钮,并将该内容放在那里。独特的内容不会通过该parent().html()进行任何更新。有人可以解释一下这是怎么回事吗?

这是每次都有效的代码:

        $(document).ready(function(){
            $("#count").click(function(e){
                e.preventDefault();

                //[... gets some parameters in here ...]

                $.post("myfile.php", {argument = list, goes = here}, function(data){
                    $("#subcount").text("Submission Count: " + data);
                });

            })
        })

这是只触发一次的代码:

        $(document).ready(function(){
            $("#count").click(function(e){
                e.preventDefault();

                //[... gets some parameters in here ...]

                $.post("myfile.php", {argument = list, goes = here}, function(data){
                    $("#subcount").parent().html(data);
                });

            })
        })

谢谢!

最佳答案

除非 data 包含 ID 为 subcount 的元素,否则在更改父 HTML 后,目标将不再存在。

尝试将数据字符串包装在:

<div id = "subcount">....</div>

然后您将获得下一次单击按钮的目标。

关于javascript - text() 与 .parent().html() 后续更改的 JQuery 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35355432/

相关文章:

javascript - 尝试访问 BigQuery 的 Oauth 客户端无效

Internet Explorer 中的 JQuery 选择器问题

html - 当元素具有不同宽度时,中间 li 元素直接居中

javascript - 如何使没有 href 属性的链接可访问?

html - 将 flex 元素右对齐

javascript - IE11 使用 AngularJS 的 ng-repeat 渲染变慢/卡住

javascript - 当 async prop Promise 解析时如何更新 React 组件?

javascript - 当属性不为空时向对象添加属性

javascript - 如何使用 jQuery Mobile 同步 setTimeout 和 mobile.navigate?

javascript - 添加覆盖后如何禁用 div 元素?