简体   繁体   English

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

[英]jquery: get value of custom attribute in drop down

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. 我需要在我的选项tage中给出的langid的值。

So what is the problem in my code. 那我的代码有什么问题呢。 ?

Secondly what is the cause of undefined error in JQuery. 其次,JQuery中未定义错误的原因是什么。

Thanks 谢谢

Inside the change handler this refers to the select element, but the langid is in the selected option element. 在更改处理程序内部, this引用了select元素,但是langid位于选定的option元素中。 So you need to find the selected option and then call .attr("langid") on that element 因此,您需要找到所选的option ,然后在该元素上调用.attr("langid")

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

Demo: Fiddle 演示: 小提琴

try something like this 尝试这样的事情

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

This script will work for you. 这个脚本适合你。 See jsfiddle jsfiddle

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM