简体   繁体   English

jQuery:从解析的html片段中选择元素

[英]jQuery: select element from parsed html snippet

Inside a class method I parse a html snippet like this: 在类方法中,我解析一个像这样的html片段:

    this.editCtrl = $('<input type="radio" name="society" value="existing"><select class="society"></select></input><input type="radio" name="society" value="existing"><input type="text"></input></input>');

I can add this snippet to my DOM and everything works fine, but before doing so I would like to fill the drop down. 我可以将这个片段添加到我的DOM中,一切正常,但在此之前我想填写下拉列表。 I tried to get it like this: 我试着像这样:

    var dropdown = this.editCtrl.find('select.society');

and like this: 和这样:

    var dropdown = $('select.society', this.editCtrl);

The length of the result set is zero in both cases. 在两种情况下,结果集的长度均为零。 What's the correct way to get a certain element from such an html snippet? 从这样的html片段中获取某个元素的正确方法是什么?

You can use filter in this case: 在这种情况下,您可以使用filter

$('<input type="radio" name="society" value="existing"><select class="society"></select></input><input type="radio" name="society" value="existing"><input type="text"></input></input>').filter(function() {
    return $(this).is('select.society')
})

Reason being that if you were to use find you would need to from the parent element of your <select> , otherwise you are directly searching the elements and not from above them. 原因是,如果你要使用find你需要从<select>的父元素,否则你直接搜索元素而不是从它们上面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM