使用 Jquery 更改下拉列表的值

change the value of dropdown using Jquery

本文关键字:下拉列表 Jquery 使用      更新时间:2023-09-26
<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="2063">Acura</option>
    <option value="2064">Honda</option>
</select>

我有一个下拉菜单。 我已经读取了链接的 HREF 属性并将其作为下拉列表的值分配。 但是我只想从链接中获取数字并将其作为值分配给下拉列表,我该怎么做。

<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="http://store.teknotik.com/category-s/2063.htm">Acura</option>
    <option value="http://store.teknotik.com/category-s/2064.htm">Honda</option>
</select>

我使用以下jQuery将链接作为值获取

$("#data a").each(function(index) {
        if ($(this).attr("class") == "subcategory_link") {

            //document.getElementsById("year").innerHTML="<option value="+$(this).attr("href")+">test</option>";
            lnk[cnt] = $(this).attr("href");
            cnt = cnt + 1;
            //alert($(this).attr("href"));
        }
    });

但我希望将下拉值设置为:

<select name="vehicle_make" onchange="test1(this.value)" style="width: 130px; float:left;" id="vehicle_make" class="home_input">
    <option value="">Choose Make</option>
    <option value="2063">Acura</option>
    <option value="2064">Honda</option>
</select>

我只想在上面的 dropdownho 中.htm之前的数字作为值发送。请指教。

简单的方法:

$('#vehicle_make option[value!=""]').each(function() {
    this.value = this.value.replace(/'D/g, "");
});​

现场演示


'd // Numerical char
'D // Not numerical char <===
g  // Is a flag which means find all the occurrences, and not only the first.

优秀的正则表达式备忘单。

所以我正在寻找所有非数字字符(带'D)并用空字符串"替换"它们。

这里好像有两个部分...只获取您想要的数字:

lnk[cnt] = $(this).attr('href').substring($(this).attr('href').lastIndexOf('/')+1);
lnk[cnt]=lnk[cnt].replace('.htm','');

(不是最优雅的解决方案,但应该有效)

然后设置值:

$("#vehicle_make").val(lnk[cnt])
你可以

像下面这样找到它;

var url = $(this).attr("href");
var urlTemp1 = url.split("/");
var urlTemp2 = (urlTemp1[urlTemp1.length -1]).split(".");
var yourNumber = urlTemp2[0];
alert(yourNumber);

尝试:


$(document).ready(function() {
  $("select[name='vehicle_make'] option[value!='']").each(function() {
     this.value = this.value.split("/").pop().split(".")[0];
  });
});

希望对你有帮助

尝试.replace('', '')函数

.replace('http://store.teknotik.com/category-s/','').replace('.htm','')

应该只给你留下数值