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

我希望每一个都有不同的行为(textbox返回文本值,select同时返回键和文本)

设置示例:

<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>

and then the script:

$('#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());

        });

推荐答案

You could do this:

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相关问答推荐

禁用提交按钮,直到所有字段都有值

如何以十六进制获取元素的背景 colored颜色 代码?

用按钮切换显示/隐藏div?

了解 Backbone.js REST 调用

为什么要两次声明 jQuery?

在 jQuery 中处理多个 ID

如何在 JavaScript 或 jQuery 中规范化 HTML?

jQuery ajax 在 asp.net mvc 中上传文件

jQuery:获取父母,父母ID?

将每 3 个 div 包装在一个 div 中

在不丢失光标位置的情况下更新输入值

更改 Eclipse 设置以忽略特定文件上的错误

如何让 twitter bootstrap 子菜单在左侧打开?

表单 propType 失败:您在没有 `onChange` 处理程序的情况下向表单字段提供了 `value` props

如何在jQuery中 Select 最后一个子元素?

如何删除集中的 contenteditable pre 周围的边框?

在jQuery中,当它们都具有相同的名称时,如何获取单选按钮的值?

使用 TypeScript 设置 window.location

'touchstart' 事件是否有与点击事件相同的 e.PageX 位置?

使用 Chosen 插件更改 Select 中的 Select