onChange不工作

时间:2013-10-30 17:23:22

标签: javascript jquery

我正在使用jquery下拉菜单。它几乎完成了,但由于某种原因,我无法让onChange工作。

<select id="cd-dropdown" class="cd-select" ONCHANGE="location = this.options[this.selectedIndex].value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>

3 个答案:

答案 0 :(得分:1)

使用location.href

<select id="cd-dropdown" class="cd-select"
        ONCHANGE="location.href = this.options[this.selectedIndex].value;" >
------------------^

<强>解释

关键字location是对象。 href对象的location属性表示URL。

完整代码:

<select id="cd-dropdown" class="cd-select" ONCHANGE="location.href = this.options[this.selectedIndex].value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>

答案 1 :(得分:1)

HTML:

<select id="cd-dropdown">
    <option disabled selected>Select</option>
    <option value="http://www.facebook.com">Facebook</option>
    <option value="http://www.google.com">Google</option>
</select>

Jquery的:

$("#cd-dropdown").on('change', function(){
    var url = $("option:selected", this).val();
    window.location = url;
});

Whenever a new value is assigned to the location object, a document will be loaded using the URL as if window.location.assign() had been called with the modified URL.

答案 2 :(得分:0)

我更喜欢这个更简单的代码:

onchange="location.href = this.value;"

此处 是选择对象。

您的代码在这里:

<select id="cd-dropdown" class="cd-select" onchange="location.href = this.value;" >
    <option value="-1" selected>Selecione uma categoria</option>
    <option value="1" class="icon-google-plus">Massa Muscular</option>
    <option value="2" class="icon-facebook">Resistência</option>
    <option value="http://www.google.com" class="icon-twitter" >Vitaminas</option>
    <option value="4" class="icon-github">Emagrecimento</option>
</select>