首页 > 解决方案 > jQuery replaceWith() 不替换新值

问题描述

我有简单的 html 代码,带有 2 个按钮和脚本,可以在单击每个按钮时替换元素。当我单击按钮 1 时,它按预期替换正确的方式。但是继续单击按钮 2 它仍然会替换单击按钮 1 时的旧值。

这是我的代码:

jQuery(document).ready(function() {
  $("button[name=btn-add]").on('click', function(e) {
    e.preventDefault();
    let Button_Id = $(this).attr("id")
    console.log(Button_Id);
    let test_content = $("#div-clone");
    stri = '<div>' + Button_Id + '</div>';
    test_content.find('#hello').replaceWith(Button_Id);
    test_content = test_content.html();
    console.log(test_content);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-success" name="btn-add" id="1">
  <i class="fas fa-plus fa-1x"></i> 
  <span style="padding-left:3px;"> button 1 </span>
</button>
<button type="button" class="btn btn-outline-success" name="btn-add" id="2">
  <i class="fas fa-plus fa-1x"></i> 
  <span style="padding-left:3px;"> button 2 </span>
</button>
<div name="div_test" id="div-clone" style="display:none">
  <span id="hello"> hello </span>
</div>

单击按钮 1 然后单击按钮 2 时:

结果:

// 1 1 // 2 1

预计:

// 1 1 // 2 2

标签: javascriptjqueryhtml

解决方案


您在第二次单击时找不到 id 为'hello'的元素,因为它已被删除。但是您可以修改您的代码以再次添加一个具有健全 id 的新 div。因此,您替换<div id="hello">hello</div><div id="hello">1</div><div id="hello">2</div>取决于您单击的按钮 ID:

jQuery(document).ready(function() {
  $("button[name=btn-add]").on('click', function(e) {
      e.preventDefault();
      let Button_Id = $(this).attr("id")
      console.log(Button_Id);
      let test_content = $("#div-clone");
      stri = '<div id="hello">' + Button_Id + '</div>';
      test_content.find('#hello').replaceWith(stri);
      test_content = test_content.text();
      console.log(test_content);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button type="button" class="btn btn-outline-success" name="btn-add" id="1">
  <i class="fas fa-plus fa-1x"></i> 
  <span style="padding-left:3px;"> button 1 </span>
</button>
<button type="button" class="btn btn-outline-success" name="btn-add" id="2">
  <i class="fas fa-plus fa-1x"></i> 
  <span style="padding-left:3px;"> button 2 </span>
</button>
<div name="div_test" id="div-clone" style="display:none">
  <span id="hello"> hello </span>
</div>


推荐阅读