[英]change text at select option value=“”
this is my code of a dynamic drop down menu and I want to change the text of the first option which has no id and the value is empty! 这是我的动态下拉菜单代码,我想更改第一个选项的文本,该选项没有id并且值为空!
this is the code: 这是代码:
<div class="my-tours">
<select name="tours">
<option value="">All</option>
<option value="america">America</option>
</select>
</div>
Your question is not clear what you want as output. 您的问题不清楚要输出什么。 but you change first option value by doing something like this :
但是您可以通过执行以下操作来更改第一选项的值:
$("#select-id option:first").attr("value", "");
$('#tours > option:not([id])').filter(function () { let val = $(this).attr('value'); return val === undefined || val === ''; }).first().text('First id-less with no value');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-tours"> <select name="tours" id="tours"> <option value="mexico">Mexico</option> <option value="">All</option> <option value="america">America</option> <option>Nowhere</option> </select> </div>
I added an id to the <select>
tag to make it simpler to select it, and make DOM queries for it more efficient. 我在
<select>
标记中添加了一个ID,以使其更易于选择,并使DOM查询更为有效。 I highly recommend doing that, but if for some reason you can't add an id, you could also select it using $('select[name="tours"]')
. 我强烈建议您这样做,但是如果由于某些原因您无法添加ID,也可以使用
$('select[name="tours"]')
选择它。
Step by step, here is what this does: 逐步操作,这是做什么的:
$('#tours > option:not([id])')
selects all of the <option>
tags inside of #tours
that do not have an id
attribute. $('#tours > option:not([id])')
选择#tours
中没有id
属性的所有<option>
标记。 .filter('[value=""]')
instead. .filter('[value=""]')
代替。 .first()
grabs the first option that matched our filter. .first()
与我们的过滤器匹配的第一个选项。 .text()
sets the new text. .text()
设置新文本。 Here it is. 这里是。 Use
name
attribute and :first
in option selector. 在选项选择器中使用
name
属性和:first
。
$(document).ready(function() { $("select[name='tours'] option:first").text("wow"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="my-tours"> <select name="tours"> <option value="">All</option> <option value="america">America</option> </select> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.