JQuery:查找和替换属性值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8729451/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:57:31  来源:igfitidea点击:

JQuery: find and replace of attribute values

jquery

提问by JJ180

I am having difficulty performing a find and replace of attribute values.

我在执行属性值的查找和替换时遇到困难。

Consider this html:

考虑这个html:

<tr id="rules[0]">
    <td>
        <input id="rules0.isActive1" name="rules[0].isActive" type="checkbox" value="true"/><input type="hidden" name="_rules[0].isActive" value="on"/>
    </td>
    <td>
        <select id="rules0.leftCondition.name" name="rules[0].leftCondition.name">
            ...
        </select>
    </td>

I am looking to update each 's name attribute with the appropriate count e.g. rules[0].isActive is updated to rules[10].isActive

我希望用适当的计数更新每个的 name 属性,例如 rules[0].isActive 更新为 rules[10].isActive

I am using this JQuery snippet:

我正在使用这个 JQuery 片段:

$(newRow).find('[id*="rules"]').each(function(){
    // Update the 'rules[0]' part of the name attribute to contain the latest count 
    this.name.replace('rules\[0\]','rules\[$count\]');
}); 

where newRow is a variable holding the entire block and count holds the latest counter value. However, when I debug this code it seems that "this.name" is undefined.

其中 newRow 是保存整个块的变量,count 保存最新的计数器值。但是,当我调试此代码时,似乎未定义“this.name”。

Where am I going wrong here?

我哪里出错了?

Thanks

谢谢

回答by kaz

To update attribute of element you should use the .attr function. Also, when using this in jQuery context you must use $(this) syntax. If I understand your intentions so it should be something like that:

要更新元素的属性,您应该使用 .attr 函数。此外,在 jQuery 上下文中使用 this 时,您必须使用 $(this) 语法。如果我理解你的意图,那么它应该是这样的:

$(newRow).find('[id*="rules"]').each(function(){
    // Update the 'rules[0]' part of the name attribute to contain the latest count 
    $(this).attr('name',$(this).attr('name').replace('rules\[0\]','rules\[$count\]'));
}); 

回答by Muru Bakthavachalam

try this: Assume row attribute name is 'filterCol' then you can set the new value to that attribute

试试这个:假设行属性名称是“filterCol”,那么你可以将新值设置为该属性

$("#trId").attr("filterCol", newValue);

回答by Erik Escobedo

You should use $(this).attr('name')instead of this.name.

你应该使用$(this).attr('name')而不是this.name.

回答by techfoobar

Try this:

尝试这个:

$(this).attr('name', $(this).attr('name').replace('rules\[0\]','rules\[$count\]'));