jQuery中替换表单元素属性的一部分

4

我想要用一个新的值替换name属性的一部分,这个新的值依赖于原始值。name属性的值为:timeslots[timeslot_1][start]

  1. 如何将值“timeslot_1”递增为“timeslot_2”,并将原始值替换为此值?

  2. cloneElm包含两种类型的元素(input和select) - 我希望能够在循环中捕获这两种元素。

到目前为止我写出的代码:

$(cloneElm).children('span').children('input').each(function(id) {
        var newName = $(this).attr('name').replace('timeslot_1', 'timeslot_2');
        $(this).attr('name', newName);
    });  

谢谢

5个回答

2

实际上,我不确定我是否走在正确的轨道上,因为我对你的问题有点困惑,但是我会试着回答。

$(cloneElm).children('span').children('input').each(function(id) {
        var mynumber = parseInt((($(this).attr('name')).split("_"))[1]);
        var newName = $(this).attr('name').replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1));
        $(this).attr('name', newName);
    });  

阅读了其他文章后,可以像这样进行优化:

$(cloneElm).find(':input').attr('name', function(i, name) {
  var mynumber = parseInt(name.split("_")[1]);
  return name.replace('timeslot_' + mynumber, 'timeslot_' + (mynumber + 1));
});  

2

我认为这种使用.attr()的一般方法是你需要的:

$(cloneElm).find(':input').attr('name', function(i, name) {
  return name.replace('timeslot_1', 'timeslot_2');
});  

0
  • 你可以将函数作为attr()的第二个参数传递,从而消除了使用each()的必要性。
  • 为了同时选择inputselect元素,你需要相应地调整你的选择器。
  • 最后,你也可以向replace()方法提供一个正则表达式和一个函数。

以下是一个结合了上述内容的例子:

$(cloneElm).children('span').children('input, select').attr("name", function () {
    return this.name.replace(/timeslot_(\d+)/, function ($0, $1) {
        return "timeslot_" + (+$1 + 1);
    });
});

0
更通用的说法是,这只是增加了所有选择和输入字段名称属性上的数字。
$(cloneElm).children('span').children('input, select').attr('name', function(i, name) {
  if ((var result = name.match(/\d+$/)) && result)
    return name.replace(/\d+$/,parseInt(result)+1));
});

0

你可以(正如许多人指出的那样)使用字符串分割和正则表达式来完成这个任务,但在我看来,这有点混乱,而且可能是不必要的。

如果你正在使用 jQuery 1.4.3 或更高版本,你可以使用 HTML5 的 data 属性来存储 HTML 元素中的数据以供以后使用[1]。

我会让你决定如何最好地选择所需的元素,但像这样的东西应该提供你需要的功能:

<script type="text/javascript">

function inc_timeslot(elem) {

    // calculate our next timeslot however we need to
    var timeslot =  $(elem).data("timeslot");

    timeslot += 1;

    // set the attribute
    $(elem).attr("name", "timeslot_" + timeslot);

    // and update the data attribute for next time
    $(elem).data("timeslot", timeslot);


}

</script>

<!-- ... -->

<input name="timeslot_1"  data-timeslot="1">

在早期版本的jQuery中,您可以使用jQuery data函数来设置数据,但这意味着您可能需要使用内联script标签。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接