简体   繁体   English

在一种方法中两次调用JQuery的html()函数不起作用

[英]Calling JQuery's html() function twice in one method does not work

My goal is to replace the contents of two table rows on a button click. 我的目标是在单击按钮时替换两个表行的内容。 I attempted this using JQuery's html function , but I cannot seem to call that function twice in the same method call. 我尝试使用JQuery的html函数进行此操作,但似乎无法在同一方法调用中两次调用该函数。 I tested the following in jsFiddle : 我在jsFiddle中测试了以下内容

HTML: HTML:

<table>
   <tr>
      <td class='textToReplace'>I want to be replaced with an input!</td>
      <td class='theButton'><input type="button" id="test" value="make editable"/></td>
   </tr>
</table>

JQuery: jQuery的:

$(document).on('click', "#test", function(e) {
   $(e.target).closest("td").html('<input type="button" value="cancel edit"/>');
   $(e.target).closest("tr").find('td.textToReplace').html('<input type="text" value="I am now editable!"/>');
});

Please note that in practice the table I'm working with will be an unknown number of rows, which is why I'm using classes and jquery selectors to drill through the dom. 请注意,实际上,我正在使用的表的行数是未知的,这就是为什么我使用类和jquery选择器来浏览dom的原因。 Either line of the method works fine in isolation, but in trying to call both, it will only execute the first line. 该方法的每一行都可以单独工作,但是在尝试调用两者时,它只会执行第一行。 Is there a restriction on calling .html() or am I simply missing something? 调用.html()有限制吗?还是我只是缺少某些东西?

Calling .html() replaces the entire DOM subtree with new elements parsed from the HTML. 调用.html()会将整个DOM子树替换为从HTML解析的新元素。

This means that the old subtree, including e.target , is no longer in the document and is has no such ancestor. 这意味着旧的子树(包括e.target )不再在文档中,并且没有这样的祖先。

You have two options: 您有两种选择:

1) Simply change the order 1)只需更改订单

$(document).on('click', "#test", function(e) {
  $(e.target).closest("tr").find('td.textToReplace').html('<input type="text" value="I am now editable!"/>');
  $(e.target).closest("td").html('<input type="button" value="cancel edit"/>');
});

2) Set the parent element before changing the dom: 2)在更改dom之前设置父元素:

$(document).on('click', "#test", function(e) {
  var elem = $(e.target).closest("tr");
  $(e.target).closest("td").html('<input type="button" value="cancel edit"/>');
  $(elem).find('td.textToReplace').html('<input type="text" value="I am now editable!"/>');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM