javascript - 将 div 元素中多个实例中找到的数字替换为另一个数字

标签 javascript jquery html regex

如您所见,我的 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/

相关文章:

javascript - 如何在刷新页面后保留最后一个JQuery DIV位置?

javascript - 存储选项卡的数据和信息

jquery - Tablesorter 2.0.3 colspan 问题

html - 根据内容/标签优化按钮宽度

javascript - 我无法通过 javascript 重置 HTML 输入字段

javascript - Web 服务 C# 返回未定义的值

javascript - 错误 Kendo UI Chart 图 e.slice 不是函数

javascript - 如何附加到 Firefox 附加组件中的文件?

javascript - JavaScript 的 getElementById() 和 getElementsByName() 函数有什么区别?

jquery - 如何使用 AJAX 和 PHP 将图像添加到数据库