JQuery: find and replace of attribute values

爷,独闯天下 提交于 2021-02-06 14:51:44

问题


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

Consider this 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

I am using this JQuery snippet:

$(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.

Where am I going wrong here?

Thanks


回答1:


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:

$(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\]'));
}); 



回答2:


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

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



回答3:


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




回答4:


Try this:

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


来源:https://stackoverflow.com/questions/8729451/jquery-find-and-replace-of-attribute-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!