【问题标题】:How to get specific div text with jQuery filter()如何使用 jQuery filter() 获取特定的 div 文本
【发布时间】:2011-01-09 13:42:09
【问题描述】:

我有以下在 ASP.NET 中继器中呈现的 html:

<div class="divDE-item" onclick="addFilter(this);">
  <span class="spnKey">Some key</span>
  <div>1234</div>
</div>

我意识到在外部 div 上单击可能不是最优雅的以 jQuery 为中心的方法。但是,考虑到我的情况,它运作良好。

这是我的 addFilter() 函数:

function addFilter(oDiv) {
  $(document).ready(function() {
    // Get and set the prefix text for the label. i.e. "Key = "
    sDEName = $(oDiv).find("span").text();
    $('#<%= lblDEName.ClientID %>').text(sDEName + " = ");

    // Get the actual filter text value. i.e. "1234"
    // sFilter = $(oDiv).text();
    var sFilter = $(oDiv).filter(function() {
        var filtered = $(this).not(".spnKey");
        return filtered
    });

    $('#<%= txtValue.ClientID %>').val(sFilter);
  });
}

目标是让输出看起来像这样(1234 是文本框的值):

一些键 = 1234

但是,我得到的输出是:Some key = Some key 1234

【问题讨论】:

    标签: jquery filter jquery-selectors


    【解决方案1】:

    您无需致电filter

    你可以直接写$('div:not(.spnKey)', oDiv).text()

    要回答您的问题,您使用的 filternot 是错误的。 filter 方法返回一个 jQuery 对象,其中包含您调用它的元素中的一些元素。 (不是他们的孩子)。要以这种方式使用它,您应该致电$(oDiv).children().filter(...)

    not方法与filter相反,返回jQuery对象中不匹配函数选择器的元素。因此你也可以写$(oDiv).children().not('.spnKey')

    【讨论】:

    • 成功了!感谢您的更正和示例,非常好。
    【解决方案2】:

    看来您的做法完全错误。试试这个——让你的中继器正常吐出代码:

    <div class="divDE-item">
      <span class="spnKey">Some key</span>
      <div>1234</div>
    </div>
    

    并使用以下 javascript 来获取值:

    $(document).ready(function() {
      $("div.divDE-item").click(function() { 
         $thisElement = $(this);
         var thisValue = $($thisElement).children("div").text();
         $('#<%= txtValue.ClientID %>').val(thisValue);
      });
    });
    

    这样,它会将点击事件应用到 DOM 预渲染中出现的每个(我猜是重复的)div 实例。也应该更轻量级。

    【讨论】:

    • 我完全同意,我一开始就尝试过这种方法。我没有成功触发点击事件。也许它与Repeater 在ListView 中有关,所有这些都在UpdatePanel 中。 UpdatePanel 可能是罪魁祸首。因此,我采用了这种公认的不太理想的方法,即 onclick 方法。不过,我很乐意以正确的方式做到这一点。感谢您的反馈。
    • 非常好,成功了。我还没来得及检查新的 live() 方法。再次感谢!
    • @Clay:没问题。 live() 并不是一个真正的新方法,它在概念上有点混乱,但非常有用。我只是将其视为可能出现在 DOM after $(document).ready() 中的对象的事件绑定器
    猜你喜欢
    • 2011-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 2020-09-05
    • 2021-05-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多