在HTMLString中找到的元素中设置attr(name)



我使用Jquery保存html_data变量HTML代码。尤其是

Jquery(document).ready(function(){
     html_data = $('.row').html();
)};

<div class = "row">
  <div class = "col-md-12">
    <select multiple="multiple" id ="sel1">
      <option value="1"> Element1 </opion>
      <option value="2"> Element2 </opion>
      <option value="3"> Element3 </opion>
    </select>
   </div>
</div>
<div class ="before"></div>

然后我在Jquery中有一个函数,我写

function newRow(){
    new_html = html_data;
    $(new_html).find('select').attr('name', 'myNewSelect');
    $(new_html).insertBefore('.before');
}

创建了具有select multiple的新row,但没有设置属性名。

您不需要获取.row元素的html()。您可以使用jquery的.clone()方法,然后使用相同的.insertbefore()方法将其附加在.before之前

function newRow(){
var new_html = $('.row .col-md-12').clone(true);
new_html.insertBefore('.before');
new_html.find('select').attr('name', 'myNewSelect');
}

这里是小提琴:https://jsfiddle.net/eL43e2vs/

最新更新