jQuery – 确定input元素是文本框还是select列表

我将如何确定jQuery中的inputfilter返回的元素是文本框还是select列表?

我想每个都有不同的行为(文本框返回文本值,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> 

然后脚本:

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

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

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

如果你想更具体,你可以testingtypes:

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

或者,您可以使用.prop检索DOM属性

这里是select框的示例代码

 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 }