【问题标题】:jQuery - determine if input element is textbox or select listjQuery - 确定输入元素是文本框还是选择列表
【发布时间】:2011-07-03 18:15:27
【问题描述】:

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

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

示例设置:

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

        });

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    如果只想检查类型,可以使用jQuery的.is()函数,

    就像我在下面使用的那样,

    if($("#id").is("select")) {
     alert('Select'); 
    else if($("#id").is("input")) {
     alert("input");
    }
    

    【讨论】:

      【解决方案2】:

      您也可以检索 DOM 属性 .prop

      这里是选择框的示例代码

      if( ctrl.prop('type') == 'select-one' ) { // for single select }
      
      if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
      

      文本框

        if( ctrl.prop('type') == 'text' ) { // for text box }
      

      【讨论】:

      • 这就像一个新的 jQuery 函数 prop() 的魅力。谢谢。
      【解决方案3】:

      你可以这样做:

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

      或者这个,它更慢,但更短更干净:

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

      如果你想更具体,你可以测试类型:

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

      【讨论】:

      • 我必须添加 jquery 语法 $(element).is('input') 才能让它工作,但总的来说很棒。
      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      相关资源
      最近更新 更多