好的,这是我的问题。我有一个具有不同值的选择下拉列表。如果我选择其中一个,模板就会被克隆到一个无序列表中。问题是,我想确保你不能克隆同一个元素两次。
在克隆的列表元素中,有一个,其内部文本与选择下拉列表中选项的相应标签相同。
唉,我试图在无序列表中找到一个标签,该标签的文本与下拉列表中当前选择的选项相同。如果有这样的标签,就不应该进行克隆。
这是我的代码:
$ ->
$('#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())
使用filter
进行精确的文本匹配:
var selectedText = selected.text();
var matches = $('option', this).filter(function() {
return $(this).text() == selectedText;
});
if (matches.length == 0){
// No match!
}
如果您需要不区分大小写,请使用带有/i
选项的构造regex,或者将两者都设为小写:
var selectedText = selected.text().toLowerCase();
var matches = $('option', this).filter(function() {
return $(this).text().toLowerCase() == selectedText;
});
if (matches.length == 0){
// No match!
}