【问题标题】:How to find a label by it's innertext in an unordered list with jquery如何使用jquery在无序列表中通过其内部文本查找标签
【发布时间】:2014-11-27 04:52:51
【问题描述】:

好的,这是我的问题。我有一个具有不同值的选择下拉列表。如果我选择其中一个,模板将被克隆到无序列表中。问题是,我想确保你不能克隆同一个元素两次。

在克隆的列表元素中,有一个内部文本与选择下拉列表中选项的相应标签相同。

唉,我尝试在无序列表中找到与下拉列表中当前选择的选项具有相同文本的标签。如果有这样的标签,就不应该继续克隆。

这是我的代码:

$ ->
  $('#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())

【问题讨论】:

    标签: javascript jquery html coffeescript


    【解决方案1】:

    使用filter 进行精确的文本匹配:

    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 :)
    猜你喜欢
    • 2011-08-11
    • 1970-01-01
    • 2014-06-27
    • 2014-12-29
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多