javascript - 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
解决方案
您在第二次单击时找不到 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>
推荐阅读
- php - 是否可以将 PHP 扩展转移到另一台 PC?
- python - 如何使用 python 子进程使用 shell 'source' 命令
- java - 如何注册在 Android (Java) 中按住的键盘键并采取相应措施
- hyperledger-fabric - Hyperledger Fabric 上的 FabCar 示例
- json - 将索引添加到 json 文件以从 firebase 获取数据时出错。无效的 JSON。键不能为空或包含 $ # [ ] / 或
- swift - 在 deinit 期间首次访问引用 self 的惰性 var 时避免崩溃
- angular - 了解角度模块导入
- javascript - TypeError:无法读取 null 的属性“dispatchEvent”
- java - 获取第一个元素并在应用函数后返回
- wordpress - 删除结帐页面上特定类别的帐户用户名和密码