javascript jquery:在下拉列表中获取自定义属性的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20266023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:07:11  来源:igfitidea点击:

jquery: get value of custom attribute in drop down

javascriptjquery

提问by Rizwan Shamsher Kaim Khani

I have a simple JQuery code.

我有一个简单的 JQuery 代码。

$(document).ready(function() { 
  $( ".translanguage" ).change(function() {
      var value = $(this).attr("langid");
      alert(value);
  });
});

and i have html code.

我有 html 代码。

<select name="translanguage" class="translanguage">
  <option value="0">Please Select Language</option>
  <option class="transoption" value="1" langid="1">Urdu</option>
  <option class="transoption" value="2" langid="2">English</option>
  <option class="transoption" value="3" langid="3">Arabic</option>
  <option class="transoption" value="4" langid="4">Sindhi</option>
</select>

When i run this program, it is giving undefined error in alert box. I need the value of langid as given in my option tage.

当我运行这个程序时,它在警告框中给出未定义的错误。我需要在我的选项标签中给出的 langid 值。

So what is the problem in my code. ?

那么我的代码有什么问题。?

Secondly what is the cause of undefined error in JQuery.

其次,JQuery 中未定义错误的原因是什么。

Thanks

谢谢

回答by Arun P Johny

Inside the change handler thisrefers to the selectelement, but the langidis in the selected optionelement. So you need to find the selected optionand then call .attr("langid")on that element

更改处理程序内部this是指select元素,但langid是在所选option元素中。所以你需要找到选定的option然后调用.attr("langid")那个元素

jQuery(function () {
    $(".translanguage").change(function () {
        var value = $(this).find('option:selected').attr("langid");
        alert(value);
    });
})

Demo: Fiddle

演示:小提琴

回答by sachin chavda

This script will work for you. See jsfiddle

这个脚本对你有用。见jsfiddle

$(function () {
    $(".translanguage").change(function () {
        var value = $( "select option:selected" ).attr("langid");
        alert(value);
    });
})

回答by rajesh kakawat

try something like this

尝试这样的事情

      $( ".translanguage" ).change(function() {
          alert(this.options[this.selectedIndex].getAttribute('langid'));
      });

回答by sreenath

try this:

试试这个:

// jquery wont find the attr of langid, change the langid to id in html.
$(document).ready(function() { 
  $( ".translanguage" ).change(function() {
    var value = $(this).attr("id");
    alert(value);
  });
});