【问题标题】:replace select indexed attributes with regexp用正则表达式替换选择索引属性
【发布时间】:2016-06-03 13:04:59
【问题描述】:

我有以下 DOM:

<select id="evo_calculatorbundle_ruletype_assertions_0_logicalOperator">...</select>
<select id="evo_calculatorbundle_ruletype_assertions_1_logicalOperator">...</select>

使用 JqueryUI 可排序组件,我正在对这些选择标签进行排序。排序后,#1 选择放在#0 选择之前。 我想根据新的 DOM 重新索引这些选择。

这是我的可排序实例:

// Sortable assertions
$collectionHolder.sortable({
    placeholder: "ui-state-highlight",
    handle: ".handle",
    helper: "original",
    cursor: "move",
    update: function(event, ui) {
        var elements = $collectionHolder.find("tr");
        var count = elements.length;
        console.log(count);

        $(elements).each(function(index) {
            $(this).data('index', index).attr('data-index', index);

            var pattern = '/_[0-9]+_/g';
            var replacement = '_' + index + '_';

            $(this).find('select').each(function(){
                var before = $(this).attr('id');
                var after = $(this).attr('id').replace(pattern, replacement);
                console.log(before + " " + after);

                $(this).attr('id', $(this).attr('id').replace(pattern, replacement));
                $(this).css('border', '3px solid black');
            });
        });
    }
});

替换不起作用,console.log(before + " " + after) 打印以下内容:

evo_calculatorbundle_ruletype_assertions_1_logicalOperator evo_calculatorbundle_ruletype_assertions_1_logicalOperator
evo_calculatorbundle_ruletype_assertions_0_logicalOperator evo_calculatorbundle_ruletype_assertions_0_logicalOperator

我期待

evo_calculatorbundle_ruletype_assertions_1_logicalOperator evo_calculatorbundle_ruletype_assertions_0_logicalOperator
evo_calculatorbundle_ruletype_assertions_0_logicalOperator evo_calculatorbundle_ruletype_assertions_1_logicalOperator

replace javascript 函数我做错了吗?还是我的模式不对?

【问题讨论】:

    标签: javascript regex indexing replace jquery-ui-sortable


    【解决方案1】:

    javascript中的正则表达式用斜杠括起来,如果用单引号括起来,它就变成了一个字符串。

    用途:

    var pattern = /_[0-9]+_/g;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-23
      • 2013-02-19
      • 2015-07-16
      • 2012-05-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多