jquery在变量中查找和替换字符串

jquery在变量中查找和替换字符串,jquery,replace,Jquery,Replace,我已经寻找了很久,似乎找不到一个答案,我认为这是一个非常简单的问题。我使用.clone()复制了一个包含多个表单字段的li,然后将其插入表单的开头。这个很好用 我试图做的是查找ROWID的所有实例,并将其替换为变量I <ul class="form"> <li class="hide"> <ol class="form"> <li><label for="cat_id_ROWID">Category:</l

我已经寻找了很久,似乎找不到一个答案,我认为这是一个非常简单的问题。我使用
.clone()
复制了一个包含多个表单字段的
li
,然后将其插入表单的开头。这个很好用

我试图做的是查找
ROWID
的所有实例,并将其替换为变量
I

<ul class="form">
<li class="hide">
    <ol class="form">
        <li><label for="cat_id_ROWID">Category:</label>
            <select id="cat_id_ROWID" name="cat_id[]">
                <option>...options...</option>
            </select>
        </li>
        <li>
            <label for="value_ROWID">Value:</label>
            <input id="value_ROWID" name="value[]">
        </li>
        <li>
            <label for="description_ROWID">Description:</label>
            <textarea id="description_ROWID" name="description[]"></textarea>
        </li>
    </ol>
</li>
</ul>

我正在尝试执行类似于
$(newitem.replace('ROWID',I)的操作但它不起作用。任何帮助都将不胜感激!谢谢。

newitem是
li
而不是属性。 试着这样做:

newitem.html(newitem.html().replace("ROWID",i));

newitem是
li
,而不是属性。 试着这样做:

newitem.html(newitem.html().replace("ROWID",i));

您的
newitem
变量是jQuery对象,而不是字符串,因此简单的
.replace
将无法工作。您必须在
newitem
中选择所需的元素,并分别更改属性(即字符串)

var $newitem = $('li.hide').eq(0).clone();
$('[for$="ROWID"]', $newitem).each(function () {
    $(this).attr('for', $(this).attr('for').replace('ROWID', i));
});
$('[id$="ROWID"]', $newitem).each(function () {
    $(this).attr('id', $(this).attr('id').replace('ROWID', i));
});
$newitem.removeClass('hide').addClass('row');
$newitem.insertBefore('ul.form li:first');

您的
newitem
变量是jQuery对象,而不是字符串,因此简单的
.replace
将无法工作。您必须在
newitem
中选择所需的元素,并分别更改属性(即字符串)

var $newitem = $('li.hide').eq(0).clone();
$('[for$="ROWID"]', $newitem).each(function () {
    $(this).attr('for', $(this).attr('for').replace('ROWID', i));
});
$('[id$="ROWID"]', $newitem).each(function () {
    $(this).attr('id', $(this).attr('id').replace('ROWID', i));
});
$newitem.removeClass('hide').addClass('row');
$newitem.insertBefore('ul.form li:first');

您也只能通过attr()函数编辑属性:)方法几乎相同!谢谢你的回复,不幸的是这对我不起作用@不过,纳奇托的解决方案已经成功。是否可以将jQuery对象展平,使其仅为html/文本而不是一系列对象?这就是您试图使用
.html()
所做的吗?如果您使用.html(),则容器中的所有内容都将作为html或.text()作为文本。然后你可以使用你想要的每一个字符串操作。然后您可以再次插入它。只要看一下,您也只能通过attr()函数编辑属性:)这几乎是相同的方式!谢谢你的回复,不幸的是这对我不起作用@不过,纳奇托的解决方案已经成功。是否可以将jQuery对象展平,使其仅为html/文本而不是一系列对象?这就是您试图使用
.html()
所做的吗?如果您使用.html(),则容器中的所有内容都将作为html或.text()作为文本。然后你可以使用你想要的每一个字符串操作。然后您可以再次插入它。只要看一眼就知道了