如何将两个下拉列表的jQuery change事件函数合并为一个?
Merging Your Dropdown Change Handlers
You can easily combine these two change event listeners into a single function that handles both AJAX loads when either dropdown changes. Here's how:
$('#Ctry,#Yd').change(function () { // Cache the dropdown values once to avoid repeated DOM lookups const ctryValue = $('#Ctry').val(); const ydValue = $('#Yd').val(); // Load content into #Rial from the "tal" action const talUrl = '@Url.Action("tal", "St")'; $('#Rial').load(talUrl, { ctry: ctryValue, yd: ydValue }); // Load content into #con from the "tala" action const talaUrl = '@Url.Action("tala", "St")'; $('#con').load(talaUrl, { ctry: ctryValue, yd: ydValue }); });
Key Notes:
- We only attach one
changeevent listener to the#Ctryand#Ydelements instead of two, keeping your code cleaner and avoiding redundant event handling. - Caching the dropdown values (
ctryValueandydValue) reduces unnecessary DOM queries, making the code slightly more efficient. - Both AJAX
load()calls still run whenever either dropdown is updated—they’re just grouped together in a single handler now, maintaining the original functionality.
内容的提问来源于stack exchange,提问作者User9895
相关产品推荐
相关产品推荐

