简体   繁体   English

Jquery将option元素的值设置为元素的文本

[英]Jquery set value of option element to be the text of the element

I need to set the value attribute of the option element equal to the text of the option element itself. 我需要将option元素的value属性设置为等于option元素本身的文本。 This is the code I have currently. 这是我目前的代码。 For some reason it is concatenating the strings. 由于某种原因,它连接字符串。

Here's the HTML markup. 这是HTML标记。

    <select id="ResidentialBuildingType" name="ResidentialBuildingType">
     <option>SFD</option>
     <option>Test</option>
    </select>

Here's the jquery code: 这是jquery代码:

    <script>
    $(document).ready(function () {
        var select = $('#ResidentialBuildingType > option');
        $(select).each(function (index) {
            console.log(select.text());
        });
    });
    </script>

Try to use the .attr() receiver function to achieve that, 尝试使用.attr()接收函数来实现这一点,

$('#ResidentialBuildingType > option').attr("value",function(){
  return $(this).text();
});

DEMO DEMO

change: 更改:

console.log(select.text());

to

console.log($(this).text());

Demo:: jsFiddle 演示:: jsFiddle

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

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