【问题标题】:Referencing the value of a variable in a jQuery selector [duplicate]在 jQuery 选择器中引用变量的值 [重复]
【发布时间】:2014-07-18 03:08:19
【问题描述】:

我想替换$('#divy a:lt(3)')并添加变量而不是数字$('#divy a:lt(count)'),但它不起作用。

Fiddle

var timerId,
count = 0;

function end_counter() {
    $('#divy a:lt(3)').each(function () {
        var $this = $(this);
        $this.attr('target', '_blank');
        $this.get(0).click(function () {
            window.open(this);
            return false;
        });
    });
    count = 0;
}
$('button').click(function () {

    count++;
    clearTimeout(timerId);
    timerId = setTimeout(end_counter, 700);
});

【问题讨论】:

  • 您的总体目标是什么?你到底想用这段代码完成什么?告诉我们您要替换 $('#divy a:lt(3)') 并没有帮助,因为我们不知道您的最终目标。
  • get(0) 返回一个DOM 对象,而不是jQuery 对象,而且因为$this.each 的主题,所以没有理由使用get,因为@无论如何,987654332@ 只是一个元素。
  • 当 3 存在时,它将打开 div 中的前 3 个 href,方法是添加一个变量名而不是我想要更改打开的 href 数量的数字,例如:count = 5,打开前5页。但是当添加变量名而不是数字时它不起作用。

标签: javascript jquery


【解决方案1】:

问题在于您的 jQuery 选择器是字符串 $("#divy a:lt(count)")。您需要做的是根据 count 的内容更改该字符串。将其更改为 $("#divy a:lt("+count+")") 应该会为您解决。这样,如果 count 为 5,您的选择器就是 $("#divy a:lt(5)")

【讨论】:

  • 没问题,很高兴它有效
【解决方案2】:

你需要有这样的东西才能工作

$('#divy a:lt('+count+')')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2011-10-05
    相关资源
    最近更新 更多