为什么不'在JQuery中找到第二个css选择器的工作

Why doesn't .find work with this second css selector in JQuery?

本文关键字:第二个 css 选择器 工作 JQuery 为什么不      更新时间:2023-09-26

当我使用name=value选择器执行.fund时,我没有得到任何元素。我的语法看起来是正确的,我看不出我做错了什么。我知道它从中选择的对象有元素,确切地说是7,具有我要查找的属性。所以我很困惑为什么这个发现不起作用。

页面上的Javascript:

$(document).ready(function () {
        var mainCatName = 'category.SelectedValue'
        $('#Button1').on('click', function () {
            var td = $('input[name="' + mainCatName + '"]:checked').parent('td');
            var tdIndex = td.index();
            if (selectElems == null) {
                //1 
                selectElems = $("#pumpConfigTable td:nth-child(" + (tdIndex + 1) + ") select,  #pumpConfigTable td:nth-child(" + (tdIndex + 1) + ") input");
            }
            var projectInfoID = $('#ProjectInfoID').attr('value');
            var mainCategoryID = $('input[name="' + mainCatName + '"]:checked').attr('value');
            var postBackObject = makeProjectInfoObjects(projectInfoID, mainCategoryID, selectElems);
            var blah = "blah";
        });

    });

makeProjectInfoObjects的部分来源:

function makeProjectInfoObjects(pInfoID, mainCatID, pcOptions) {
    //var pc = new PumpConfig();
    var pc = new Array();
    var dbIDs = _.pluck(pcOptions, "data-dbid");
    var uniquedbIDs = _.unique(dbIDs);
    uniquedbIDs = _.reject(uniquedbIDs, function (checkID) { return checkID == undefined; });
    var len = uniquedbIDs.length;
    for (var i = 0; i < len; ++i) {
        //2
        var categories = $(pcOptions).find("[data-dbid='" + uniquedbIDs[i] + "']");
        var uniqueNames = _.pluck(categories, "name");
        var singleOptions = $(categories).find(':not([name]');
        var soLen = singleOptions.length;
        for (var j = 0; j < soLen; ++j) {
            pc.push({
                pcID: uniquedbIDs[i],
                pInfoID: pInfoID,
                configCatID: mainCatID,
                configSubCatID: $(singleOptions[i]).attr('data-subcatid'),
                configValue: $(singleOptions[i]).attr('value')
            });

我在XP上使用JQuery 1.8.1和IE8。

根据IE Developer Tools的说法,第一个选择器是这样的(而且它很有效)://1 "#pumpConfigTable td:nth-child(2) select, #pumpConfigTable td:nth-child(2) input"

第二个选择器是这样的(它不起作用)://2 "#pumpConfigTable td:nth-child(2) select, #pumpConfigTable td:nth-child(2) input [data-dbid='1']"

如果您希望查找具有特定属性data-dbidinputselect元素,则不应使用find(),因为此方法搜索的元素是您用选择器字符串选择的元素的后代

"#pumpConfigTable td:nth-child(" + (tdIndex + 1) + ") select,  #pumpConfigTable td:nth-child(" + (tdIndex + 1) + ") input"

您匹配的元素将是select元素和input元素。我认为我的假设是正确的,你想在这个集合中找到特定的元素?如果是这样,请尝试使用jQuery的filter()方法,而不是find。

.滤波器(选择器)

返回:jQuery

描述:将匹配的元素集减少为与选择器匹配或通过函数测试的元素。

所以你会这样做:

var categories = $(pcOptions).filter("[data-dbid='" + uniquedbIDs[i] + "']");

如果您希望input具有data-dbid='1',则需要移除两者之间的空间:

"#pumpConfigTable td:nth-child(2) select, #pumpConfigTable td:nth-child(2) input[data-dbid='1']"