繁体   English   中英

如何确定jQuery中匹配元素的元素类型?

[英]How can I determine the element type of a matched element in jQuery?

我通过ID名称匹配ASP.Net生成的元素,但是有些元素可能会根据页面上下文呈现为文本框或标签。 我需要弄清楚是匹配到文本框还是标签,以便知道是通过val()还是通过html()获得内容。

$("[id$=" + endOfIdToMatch + "]").each(function () {
    //determine whether $(this) is a textbox or label
    //do stuff
});

我发现了一个无效的解决方案,它只会返回“ undefined”:

$("[id$=" + endOfIdToMatch + "]").each(function () {
    alert($(this).tagName);
});

我想念什么?

只是一个jQuery太多了:

$("[id$=" + endOfIdToMatch + "]").each(function () {
    alert(this.tagName);
});

考虑不使用each()的解决方案:

var elements = $("[id$=" + endOfIdToMatch + "]");
var vals = elements.is("input").val();
var htmls = elements.is("label").html();
var contents = vals.concat(htmls);

看看is的文档。

您还可以使用以下方式:

if ($(this).is('input:checkbox'))

将“ this”替换为所需的任何实例,将“ checkbox”替换为所需的任何输入类型。

第一次我回答了自己的问题。 经过更多的实验:

$("[id$=" + endOfIdToMatch + "]").each(function () {
   alert($(this).attr(tagName));
});

作品!

tagName真是个不错的提示。 我还建议使用tagName.toLowerCase(),因为返回的值取决于文档类型(HTML或XML / XHTML)。

请参阅: http//reference.sitepoint.com/javascript/Element/tagName

在jQuery 1.6中使用prop()

var el = $('body');

if (el.prop('tagName') === 'BODY') {
    console.log('found body')
}

这是获取元素类型的最佳方法

function tgetelementType( elmentid )
{

    var TypeName = $('#' + elmentid).get(0).tagName;
    var TypeName2 = $('#' + elmentid).get(0).type;


    if($('#' + elmentid).get(0).tagName== "INPUT")
    {
       return $('#' + elmentid).get(0).type.toUpperCase()
    }
    else 
    {
        return $('#' + elmentid).get(0).tagName.toUpperCase() ; 
    }
}
$("[id$=" + endOfIdToMatch + "]").each(function(){
    var $this=jQuery(this),ri='';
    switch (this.tagName.toLowerCase()){
        case 'label':
            ri=$this.html();
            break;
        case 'input':
            if($this.attr('type')==='text'){ri=$this.val();}
            break;
        default:
            break;
    }
    return ri;
})

问题是,确定标签名称后您打算做什么? 您可以使用与.end()结合使用的其他选择器轻松过滤jquery列表,以执行相同的操作:

$("[id$=" + endOfIdToMatch + "]")
    .find("input:text")
    .each(function(){
         /* do something with all input:text elements */
    })
    .end()
    .find("label")
    .each(function(){
        /* do something with label elements */
    })
    .end()

如果您需要使用此特定的元素集合做进一步的事情,则仍可以将其链接起来……就像上面的示例一样。

无论哪种情况,您都必须在each()语句中使用值做一些事情

可以说更为优雅的另一种解决方案是为每种元素类型编写两个单独的函数:

$("input#" + id).each(function() { alert(this + " is an input"); });
$("label#" + id).each(function() { alert(this + " is a label"); });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM