[英]How to trigger jQuery change event on dropdown with same value
即使用戶選擇相同的值,如何每次都觸發jQuery更改事件? 我需要一個刷新的效果例如,如果用戶選擇律師 ,並警告hello
然后再用戶從下拉菜單中選擇律師 ,它應該提醒hello
。 我怎樣才能實現它? 以下是代碼。
jQuery的
function filterPullDown () {
alert('hello');
}
$(".businessTypePullDown").change(filterPullDown);
HTML
<select class="businessTypePullDown">
<option value="" disabled selected>Business Type</option>
<option value="1">General</option>
<option value="2">Lawyer</option>
<option value="3">Software Development</option>
<option value="4">Auto-repair</option>
</select>
這應該工作。 它是標志和點擊事件的組合。 單擊選項時將始終觸發它。
<select class="businessTypePullDown">
<option value="" disabled selected>Business Type</option>
<option value="1">General</option>
<option value="2">Lawyer</option>
<option value="3">Software Development</option>
<option value="4">Auto-repair</option>
</select>
(function () {
var filterPullDown = function() {
alert('clicked');
}
var flag = false;
$(".businessTypePullDown").click(function () {
if (flag) {
filterPullDown()
}
flag = !flag;
});
$(".businessTypePullDown").focusout(function () {
flag = false;
});
}());
我想@MrUpsidown剛剛在不知情的情況下回答了這個問題! 為什么不在選項元素本身而不是外部select元素屬性上添加事件處理程序。
回到超人的代碼,使用:
$(".businessTypePullDown option").on("click", filterPullDown);
無論是否選擇了相同的值,它都會調用'filterPullDown'函數。
使用
$(".businessTypePullDown>option:not(:disabled)").click(filterPullDown);
希望這有助於某人。
因此,一旦用戶單擊選擇,以下代碼將使禁用選項成為選擇因此模仿用戶正在更改其選擇的狀態,並且因為<select>
上的.change()
事件僅在選擇選項時觸發更改(不保持不變)並且用戶無法選擇已禁用的選項,這確保始終發生更改事件,然后您可以將回調附加到.change()
事件。
$('select').on('click', function () {
$(this).find('option').attr('selected', false);
$(this).find('option:disabled').attr('selected', true);
// replace options:disabled to options:first-child
// if you don't want to pollute the select options.
});
使用以下html:
<select title="Sort By">
<option disabled>Sort By</option>
<option selected>Name</option>
<option>Date</option>
<option>Price</option>
</select>
只是
function filterPullDown () {
console.log(this.selectedIndex);
}
$(".businessTypePullDown").on('click', filterPullDown);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.