【问题标题】:Accesing the id attribute of the select tag from jquery从jquery访问select标签的id属性
【发布时间】:2012-06-10 02:57:03
【问题描述】:

我正在寻找一种从 jquery 访问 select 标记的 id 属性的方法。

说我在表单上有一个选择标签:form.php

<select id="testid">
<option value="1">1</option>
<option value="2">2</option>
</select>

从 jquery 我可以访问选项值$(this).attr("value")。但是$(this).attr("id") 未定义。

通过为选项标签提供一些 id 属性值,它可以工作。但是,有没有办法通过 $(this) 对象访问选择标签的 id

感谢您的帮助

【问题讨论】:

  • 部分代码可以帮助我们添加你的html和js代码,谢谢。
  • 尝试$(this)[0].id,如果它仍然未定义,则该元素可能没有 ID。就像@vchakoshy 说的......我们需要代码。
  • 在事件处理程序中this 将指向事件绑定到的元素。您需要澄清您尝试获取该 ID 的事件。

标签: php jquery


【解决方案1】:

如果您在selectchange 事件中尝试,它将如下所示:

$('select').change(function() {

    // here 'this' point to select

   console.log( $(this)[0].id );

   //OR simply

   console.log(this.id);

})

$(this).attr('id') 也应该可以工作。

如果你的$(this) 指向option 然后试试

$('select').has(this).attr('id');

$(this).parent('select').attr('id');

【讨论】:

  • 我试过 $(this).parent('select').attr('id');但它不起作用。
  • 对不起,它有效。代码中有问题导致它不起作用。感谢@thecodeparadox 的帮助
【解决方案2】:

可能是 $(this).attr("id") 中的 this 指向 option 元素。

试试这个,

var id;
if(this.tagName === 'option'){
    id = $(this).parent().attr('id');
}
else{
   id = $(this).attr("id");
}

【讨论】:

    【解决方案3】:

    尝试:

    $(this)[0].id
    

    this.id
    

    【讨论】:

      【解决方案4】:

      你可以试试这个!

      <select id="testid">
      <option class='option' value="1">1</option>
      <option class='option' value="2">2</option>
      </select>
      
      $(document).ready(function(){
      
      $("#testid").change(function(){
      var option = [];
      
      $("option.option:selected").each(function(i){// this will filter the selected id
      
      option[i] = $(this).val();
      });
      alert(option);
      });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-03-08
        • 2016-09-04
        • 2013-09-17
        • 2020-02-08
        • 1970-01-01
        • 2023-03-16
        • 2019-11-23
        • 1970-01-01
        相关资源
        最近更新 更多