Javascript 如何使用jquery通过无序列表中的innertext查找标签
好的,这是我的问题。我有一个带有不同值的选择下拉列表。如果我选择其中一个,模板将克隆到无序列表中。问题是,我想确保你不能克隆同一个元素两次 在克隆的列表元素中,有一个内部文本,该文本与“选择”下拉列表中选项的相应标签相同 唉,我试图在无序列表中找到一个标签,其文本与下拉列表中当前选择的选项相同。如果有这样的标签,则不应继续克隆 这是我的密码:Javascript 如何使用jquery通过无序列表中的innertext查找标签,javascript,jquery,html,coffeescript,Javascript,Jquery,Html,Coffeescript,好的,这是我的问题。我有一个带有不同值的选择下拉列表。如果我选择其中一个,模板将克隆到无序列表中。问题是,我想确保你不能克隆同一个元素两次 在克隆的列表元素中,有一个内部文本,该文本与“选择”下拉列表中选项的相应标签相同 唉,我试图在无序列表中找到一个标签,其文本与下拉列表中当前选择的选项相同。如果有这样的标签,则不应继续克隆 这是我的密码: $ -> $('#add_feature').change -> //#add_feature is the id of my s
$ ->
$('#add_feature').change -> //#add_feature is the id of my select option dropdown
features = $('ul#features') //features is the unordered list, where i append my
//cloned list elements
...
selected = $(this).find('option:selected') //here i find the currently selected
//option
//this is where i want to have an if clause or something that compares the
//inner text of all the labels in the UL to the text of the currently
//selected option
//this is the cloning procedure which should only be called if there is
//no label found above
feature = $('#template_feature li').clone()
features.append(feature)
$(feature).find('#home_features_attributes_new_type').val(selected.data('type'))
$(feature).find('#home_features_attributes_new_name').val($(this).val())
$(feature).find('label[for="home_features_attributes"]').prepend(selected.text())
使用过滤器进行精确的文本匹配:
var selectedText = selected.text();
var matches = $('option', this).filter(function() {
return $(this).text() == selectedText;
});
if (matches.length == 0){
// No match!
}
如果需要不区分大小写,请使用带/i选项的构造正则表达式,或者将两者都设置为小写:
var selectedText = selected.text().toLowerCase();
var matches = $('option', this).filter(function() {
return $(this).text().toLowerCase() == selectedText;
});
if (matches.length == 0){
// No match!
}
嗯,这似乎对我没什么好处。也许我把它从JS转换成CoffeeScript是错误的,尽管我用了一个转换器仔细检查了一下。如果你能发布一个新的代码,我会查找拼写错误。我是凭记忆写的,所以没有现场测试。我也可以看到实际的HTML: