javascript - 将变量放入 Jquery 选择器中

标签 javascript jquery

我只想动态放入索引,该索引计算正确,所以我知道我的变量的值不是问题,但它不起作用:

我的变量“parentIndex”存储我想要在下面选择的范围的索引。我已经测试了这个变量并且它返回正确的值。

$(".DropDownMenu span:eq("+parentIndex+")")

这不是将变量放入 jquery 选择器的正确方法吗?我发现的所有示例都使用这种格式,我缺少什么?

(整个函数,用于上下文:)

        $("span input:radio").click(function() {
        if (($(this).is(":checked")) == true) {
            var elem = $(this);
            var parent = $(this).parent();
            var aunts = parent.parent().children();
            var parentIndex = aunts.index(parent);
            var position = elem.position();
            var topValue = position.top;
            topValue = topValue - 9;
            $(".DropDownMenu").css({ "top": "-" + topValue + "px" });
            $(".DropDownMenu span").css("background-image", "none");
            parent.css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });
            $(".DropDownMenu span:eq("+parentIndex+")").css({ "background": "#f3f1e7 url(assets/images/branding/DropDownArrow.gif) no-repeat right" });

        }
    });

最佳答案

试试这个方法:

$(".DropDownMenu span").eq(parentIndex)

您可以在docs here中找到更多详细信息。 .

但是,您的应该按原样工作,请确保使用 FireBug 来测试它,并且可以尝试使用不太复杂的函数来测试其功能。

<小时/>

如果 JS 有类似 sprintf 的东西,那就太酷了,你可以这样做: $(".DropDownMenu span:eq(%parentIndex)"

但这只是一厢情愿的想法。

关于javascript - 将变量放入 Jquery 选择器中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1930314/

相关文章:

javascript - JS 时间跟踪器未按预期工作

javascript - 将文件上传到 Amazon S3 并出现 Dropzone.js 问题

javascript - AngularJS 中存在竞争条件吗?

php - 将 PHP 输出传递给 jQuery

jquery - 滚动经过 x 像素后执行函数

javascript - window.postmessage() 在不同选项卡中的应用程序之间进行通信

javascript - 如何在 JavaScript 中遍历表格行和单元格?

javascript - 在每条语句中传入 For 循环参数

php - 如何使用 jQuery 从 php 文件中获取某些内容?

jQuery 遍历