How can I add an option in the beginning?

守給你的承諾、 提交于 2019-12-19 08:02:41

问题


I have html select,

<select id="myselect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

I need to add new option in this select. If I try like this:

$('#myselect').appendTo($('<option>my-option</option>')); 

the my-option have added to the end

<select id="myselect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>my-option</option>
</select>

How can I add an option in the beginning (as first)? Like this:

<select id="myselect">
    <option>my-option</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

回答1:


First, you mean append, rather than appendTo. append adds the content of the parameter to the selection; appendTo appends the selection to the element designated in the parameter.

Second, perhaps intuitively, you can use prepend:

$('#myselect').prepend($('<option>my-option</option>')); 



回答2:


In POJS you'd use insertBefore(), e.g.

var select = document.getElementById('mySelect');
var opt = new Option('', 'my-option');
select.insertBefore(opt, select.firstChild);



回答3:


Use prependTo()

$('#myselect').prependTo($('my-option'));//typo? 
You might have meant this

$('#myselect').prepend($('<option>my-option</option>'));  

http://api.jquery.com/prependTo

http://api.jquery.com/prepend/

But your code is actually the other way around. This might be a typo. In any case, the methods available are prepend() and prependTo()



来源:https://stackoverflow.com/questions/5934113/how-can-i-add-an-option-in-the-beginning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!