如何使用jQuery更改元素的名称和id

How to change name and id of element using jQuery?

本文关键字:id 元素 何使用 jQuery      更新时间:2023-09-26

我是jQuery新手。我克隆一个特定的HTML块,并试图改变最后克隆HTML的元素的nameid, class,但我不能。我可以找到并警告元素的名称,我想改变,但我不能改变它。希望你能帮助我…提前谢谢。

我的代码
jQuery(document).on("click",".smclass",function(){
var html = jQuery(this).closest(".entry-edit").clone().appendTo(".main-col-inner").html();
html = jQuery(html).find('.start').attr('name','optional[2][type]').attr('id', 'Type1');
 }
HTML

<div class="entry-edit">
<!-- html codes -->
<button id="Addfield" title="Field Ekle" type="button" class="smclass" onclick="" style="float: right;"><span><span><span>Field Ekle</span></span></span></button>
<!-- html codes -->
<select id="Type" name="optional[1][type]" class="start">
    <option value="0">Date</option>
    <option value="1">Text</option>
    <option value="2">Select</option>
</select>
<!-- html codes -->
</div>

您的代码只是将html字符串放入变量中,然后使用所述html创建新的jQuery对象。您没有选择新元素并更改它

//Just remove the .html() call and you will have the cloned element
var ele = jQuery(this).closest(".entry-edit").clone().appendTo(".main-col-inner");
ele.find('.start').attr('name','optional[2][type]').attr('id', 'Type1');

你也不需要多次调用。attr,你可以给它传递一个你想要设置的名称值对的对象

ele.find(".start").attr({
   "name":"optional[2][type]",
   "id":"Type1"
});

试着反过来看

var clonedObject = jQuery(this).closest(".entry-edit").clone();
clonedObject .find('.start').attr('name','optional[2][type]').attr('id', 'Type1');
clonedObject.appendTo(".main-col-inner").html();