jQuery-确定输入元素是文本框还是选择列表 [英] jQuery - determine if input element is textbox or select list

查看:68
本文介绍了jQuery-确定输入元素是文本框还是选择列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何确定jQuery中:input过滤器返回的元素是文本框还是选择列表?

How would I determine whether the element returned by an :input filter in jQuery is a textbox or select list?

我希望每种行为都有不同(文本框返回文本值,选择返回键和文本)

I want to have a different behavior for each ( textbox returns text value, select returns both key and text)

示例设置:

<div id="InputBody">
<div class="box">
    <span id="StartDate">
        <input type="text" id="control1">
    </span>
    <span id="Result">
        <input type="text" id="control2">
    </span>
    <span id="SelectList">
        <select>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
    </span>
</div>
<div class="box">
    <span id="StartDate">
        <input type="text" id="control1">
    </span>
    <span id="Result">
        <input type="text" id="control2">
    </span>
    <span id="SelectList">
        <select>
            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
        </select>
    </span>
</div>

然后是脚本:

$('#InputBody')
    // find all div containers with class = "box"
    .find('.box')
    .each(function () {
        console.log("child: " + this.id);

        // find all spans within the div who have an id attribute set (represents controls we want to capture)
        $(this).find('span[id]')
        .each(function () {
            console.log("span: " + this.id);

            var ctrl = $(this).find(':input:visible:first');

            console.log(this.id + " = " + ctrl.val());
            console.log(this.id + " SelectedText = " + ctrl.find(':selected').text());

        });

推荐答案

您可以执行以下操作:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

或这样,速度较慢,但​​更短且更干净:

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}


如果您想更具体一点,可以测试一下类型:


If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

这篇关于jQuery-确定输入元素是文本框还是选择列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆