【问题标题】:Data attribute doesn't change value on each iteration using jQuery使用 jQuery 的每次迭代时数据属性都不会改变值
【发布时间】:2020-11-04 00:00:48
【问题描述】:

执行列表搜索时,每次迭代的关键字都不会改变。 关键字是使用 HTML 代码中的数据属性添加的(它是从数据库中呈现的,因此更改 li 将具有不同的关键字)。所以在每次迭代中,关键字保持不变,搜索不起作用(我的猜测)。

JS 代码

 function search_card() {
        var input, filter, txtvalue, key;
        input = document.getElementById('txtsearch');
        filter = input.value.toLowerCase();  
        $('.product_card').each(function(){
            key = $('.ProductNameBlock').data('keywords');
            if (key.toLowerCase().indexOf(filter) > -1) {
                $('.product_card').css('display','');
            }
                else {
                $('.product_card').css('display','none');
                }         
        });              
    }

使用的关键字

  • txtsearch - 输入 id
  • product_card - li 类名
  • ProductNameBlock - 呈现数据关键字的 div 类名称(<div class="ProductNameBlock" data-keywords="<%# Eval("KeyWords")%>">(来自 db 的值)

每次迭代的关键字可以有不同的值 例如:数据优先、数据收集、特色应用 我不知道正确的格式。我该怎么办?

【问题讨论】:

  • 你需要 key = $(this).find('.ProductNameBlock').data('keywords'); 而不是,$('.ProductNameBlock') 匹配该类的所有 div。接下来你需要$(this).css(...)(同样,你隐藏/显示所有卡片)
  • 一切正常。谢谢兄弟@ChrisG

标签: javascript jquery asp.net search custom-data-attribute


【解决方案1】:

这是正确的方法

function search_card() {
        var input, filter, txtvalue, key;
        input = document.getElementById('txtsearch');
        filter = input.value.toLowerCase();  
        $('.product_card').each(function(){
            key = $(this).find('.ProductNameBlock').data('keywords');
            if (key.toLowerCase().indexOf(filter) > -1) {
                $(this).css('display','');
            }
                else {
                $(this).css('display','none');
                }         
        });              
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2011-10-11
    • 2019-05-02
    • 2011-08-16
    • 1970-01-01
    相关资源
    最近更新 更多