我有一个列表选项列表包含onchange =" setLocation(this.value)"
<div class="sort-by">
<select onchange="setLocation(this.value)">
<option value="http://example.com/test.html?dir=asc&order=position">Position</option>
<option value="http://example.com/test.html?dir=asc&order=name">Name</option>
<option value="http://example.com/test.html?dir=asc&order=price">Price</option>
<option value="http://example.com/test.html?dir=asc&order=created_at" selected="selected">Date</option>
<option value="http://example.com/test.html?dir=asc&order=end_date">End date</option>
<option value="Range">Range</option>
</select>
</div>
我之后会有一些jQuery会附加一些值
selectValues = { "Range": "Range" };
jQuery.each(selectValues, function(key, value) {
jQuery('.sort-by select').append(jQuery("<option></option>").attr("value", key).text(value));
});
当用户选择特定的我想取消setLocation
并执行其他操作
jQuery(document).ready(function(){
jQuery('.sort-by select').change(function(){
var selectedVal = jQuery(".sort-by select option:selected").val();
if (selectedVal == "Range") {
return false;
}
});
});
我该怎么做?
答案 0 :(得分:0)
使用removeAttr
并删除onClick事件。
$('select').removeAttr('onchange');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select onchange="setLocation(this.value)">
<option value="http://example.com/test.html?dir=asc&order=position">Position</option>
<option value="http://example.com/test.html?dir=asc&order=name">Name</option>
<option value="http://example.com/test.html?dir=asc&order=price">Price</option>
<option value="http://example.com/test.html?dir=asc&order=created_at" selected="selected">Date</option>
<option value="http://example.com/test.html?dir=asc&order=end_date">End date</option>
<option value="Range">Range</option>
</select>
答案 1 :(得分:0)
删除onchange属性
<div class="sort-by">
<select>
<option value="http://example.com/test.html?dir=asc&order=position">Position</option>
<option value="http://example.com/test.html?dir=asc&order=name">Name</option>
<option value="http://example.com/test.html?dir=asc&order=price">Price</option>
<option value="http://example.com/test.html?dir=asc&order=created_at" selected="selected">Date</option>
<option value="http://example.com/test.html?dir=asc&order=end_date">End date</option>
<option value="Range">Range</option>
</select>
</div>
更改if语句
jQuery(document).ready(function(){
jQuery('.sort-by select').change(function(){
var selectedVal = jQuery(".sort-by select option:selected").val();
if (selectedVal != "Range") {
setLocation(selectedVal);
}
});
});
答案 2 :(得分:0)
您可以清空属性并取消绑定事件
Jquery pre 1.7
$('select').attr('onchange','').unbind('onchange');
Jquery发布1.7
$('select').prop('onchange','').unbind('onchange');
或者你可以做 removeAttr 也取决于你的执行方式
jQuery(document).ready(function(){
jQuery('.sort-by select').change(function(){
var selectedVal = jQuery(".sort-by select option:selected").val();
if (selectedVal == "Range") {
return false;
}
$(this).attr('onchange','').unbind('onchange'); // or .prop()
});
});