如您所见,我的 HTML 包含多个对“0”的引用。我需要将它们更改为“1”。
但是,我的 jQuery 无法正常工作。
jQuery(".create-new-location").click(function() {
jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="header-logo" class="header-title location-header-0 title-edit-header" data-row-id="location-header-0" title="Location name (for your reference)">
<div class="input-selection title-edit-header">
<div class="text-input">
<input class="option_textbox col-sm-12 change-width title-edit" placeholder="Location name (for your reference)" value="" type="text" name="bp_theme_options[social][map][locations][0][location_name]">
</div>
</div>
<div class="open-block pencil-edit" data-row-id="location-header-0"></div>
</div>
最佳答案
你必须像这样设置 html
jQuery(".create-new-location").click(function() {
var the_html = jQuery("#header-logo").html().replace(/\[0\]/g, '['+(1)+']');
jQuery("#header-logo").html(the_html);
});
但这不是一个好的做法!!
当您只需要更改 <input>
的属性时,为什么要整体改变#header-logo
, 正确的?当您像这样重新绘制 html 时,您有风险丢失绑定(bind)到刚刚重新绘制的元素的事件处理程序。
jQuery(".create-new-location").click(function() {
var elements = jQuery("#header-logo").find('input[name]'); /*all input with name*/
elements.each(function(el){
var the_name = el.attr('name').replace(/\[0\]/g, '['+(1)+']');
el.attr('name', the_name);
});
});
关于javascript - 将 div 元素中多个实例中找到的数字替换为另一个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48911401/