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

前端 未结 9 1347
鱼传尺愫
鱼传尺愫 2020-12-01 03:13

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. I need to figure out wh

9条回答
  •  自闭症患者
    2020-12-01 03:46

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

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

提交回复
热议问题