简体   繁体   English

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

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

I'm matching ASP.Net generated elements by ID name, but I have some elements which may render as text boxes or labels depending on the page context. 我通过ID名称匹配ASP.Net生成的元素,但是有些元素可能会根据页面上下文呈现为文本框或标签。 I need to figure out whether the match is to a textbox or label in order to know whether to get the contents by val() or by html(). 我需要弄清楚是匹配到文本框还是标签,以便知道是通过val()还是通过html()获得内容。

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

I found a solution that doesn't work, it just returns "undefined": 我发现了一个无效的解决方案,它只会返回“ undefined”:

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

What am I missing? 我想念什么?

Just one jQuery too much: 只是一个jQuery太多了:

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

Consider this solution without using each() : 考虑不使用each()的解决方案:

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

Have a look at the documentation for is . 看看is的文档。

you could also use something like this: 您还可以使用以下方式:

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

replace "this" with whatever instance you need and 'checkbox' with whatever input type you need. 将“ this”替换为所需的任何实例,将“ checkbox”替换为所需的任何输入类型。

First time I've answered my own question. 第一次我回答了自己的问题。 After a little more experimentation: 经过更多的实验:

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

works! 作品!

tagName what a nice tip. tagName真是个不错的提示。 I would like to suggest also to use tagName.toLowerCase() since the value returned depends on the document type (HTML or XML/XHTML). 我还建议使用tagName.toLowerCase(),因为返回的值取决于文档类型(HTML或XML / XHTML)。

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

in jquery 1.6 use prop() 在jQuery 1.6中使用prop()

Example

var el = $('body');

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

This the best way to Get the element type 这是获取元素类型的最佳方法

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;
})

The question is, what do you intend to do after you've determined the tag name? 问题是,确定标签名称后您打算做什么? You could just as easily filter the jquery list using an additional selector combined with .end() to do the same thing: 您可以使用与.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()

This could still be chained if you needed to do further things with this particular collection of elements...just like the example above. 如果您需要使用此特定的元素集合做进一步的事情,则仍可以将其链接起来……就像上面的示例一样。

In either case, you'd have to do something with the values while inside the each() statements 无论哪种情况,您都必须在each()语句中使用值做一些事情

Yet another solution, arguably more elegant, is to write two separate functions for each element type: 可以说更为优雅的另一种解决方案是为每种元素类型编写两个单独的函数:

$("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