简体   繁体   English

在选择选项值=“”处更改文本

[英]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>标记。
  • The filter function filters out any options that have a value attribute that is not empty. 筛选器功能会筛选出具有不为空的value属性的所有选项。 I had to use a function to account for both options with no value attribute at all and ones that have an empty value attribute. 我必须使用一个函数来说明根本没有value属性的两个选项和具有空value属性的两个选项。 If you can be guaranteed that all of the options will have a value attribute, you could use a selector .filter('[value=""]') instead. 如果可以确保所有选项都具有value属性,则可以使用选择器.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.

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