0

我的代码是这样的:

<div class="features">
    <ul class="featuresTest">
        <li id='chklist1'><input id='Checkbox1' type='checkbox' checked /></li>
        <li id='chklist2'><input id='features2' type='textbox' /></li>
        <li id='chklist3'><input id='Checkbox1' type='checkbox' checked /></li>
    </ul> 
</div>

在我的代码中,这些复选框和文本框是使用 Jquery 动态生成的。

现在我$.each()用来查找无序(ul 标签)列表中的哪个列表(li 标签)包含文本框和复选框。

此搜索必须根据 ul 标签内的 li 标签的 id 进行。

  $("#textbutton").click(function () {


                $.getJSON('@Url.Action("GetFeaturePkId")', function (featurepkid) {

                    var featurespkid = featurepkid;
                    $.each(featurepkid, function (k,v) {
                        if ($(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]')) {
                            alert("textbox");
                        }
                        else  {
                            alert("checkbox");
                        }
                    });
                });
            });

在上面的代码中,featurepkid 返回 1 到 20。

我试过这个,但失败了。

请就这个问题给我建议。

4

4 回答 4

0

当你编辑你的问题时,我发现你的 javascript 代码有问题。

在你身上if你有$(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]')..并且返回元素数组......如果jQuery选择器没有找到任何东西,它返回空数组 - []

所以语句比较真/假......但是当他得到空数组时 -[]他将它转换为[].toString()并且返回空字符串......那就是true

所以要回答你应该更换的问题

if ($(".featuresTest > li.chklist" + v + "").has('input[type="textbox"]'))

if ($(".featuresTest > li#chklist" + v).has('input[type="textbox"]').length)

.length将返回数组中的元素计数......所以当 jQuery 选择器找不到任何东西时,它返回 0 而false不是true因为空数组。

于 2013-06-21T14:27:28.050 回答
0

您可以使用 jQuery:has选择器:

$('.featuresTest > li:has(input[type=checkbox]):has(input[type=textbox])')

编辑:如果你想liul其中找到包含这种(复选框/文本框)input类型之一,你可以使用多重选择器(“selector1,selector2,selectorN”)

$('.featuresTest > li:has(input[type=checkbox]), .featuresTest > li:has(input[type=textbox])')

现在您可以应用.each()方法来查找 ID:

.each(function() {
    console.log( $(this).attr('id') );
});

jsFiddle 示例

于 2013-06-21T13:07:19.163 回答
0

要获取li标签,您可以这样做:

var liCheck = $('.featuresTest li').filter(function(){
    return $(this).children('[type=checkbox]').length;
})
var liText = $('.featuresTest li').filter(function(){
    return $(this).children('[type=textbox]').length;
})
于 2013-06-21T13:04:13.833 回答
0

您可以检查 tagName 属性

$(".featuresTest > li").each(function () {
    console.log($(this).children('input').tagName);
});

你也可以使用.has()jQuery的功能

$(".featuresTest > li").has('input[type="checkbox"]').each(function () {
       // iterate over li's with checkboxes
});

$(".featuresTest > li").has('input[type="textbox"]').each(function () {
       // iterate over li's with textbox
});

编辑:

在回应您的评论时,我会说尝试使用 children 而不是 has 并检查长度

$.each(featurepkid, function (k, v) {
    var $elem = $(".featuresTest > li#chklist" + v);
    if ($elem.children('input[type="textbox"]').length) {
        alert("textbox");
    } else {
        alert("checkbox");
    }
});
于 2013-06-21T13:04:49.510 回答