我有一个下拉菜单,当用户选择一个选项时,它应该发出警报。我是这样写的:
function changeddl($this) {
if ($this.value == "New Posting") {
alert("Please attach supporting document(s) below.");
}
}
function changedd2($this) {
if ($this.value == "SpecialPay") {
alert("Please attach supporting document(s) below.");
}
}
function changedd3($this) {
if ($this.value == "DataEntry") {
alert("Please attach supporting document(s) below.");
}
}
function changedd4($this) {
if ($this.value == "CreditCardACHPosting") {
alert("Verify CCD or Banking Information has been added.");
}
}
有没有办法将所有人合并?
谢谢。
答案 0 :(得分:0)
根据您的代码,您可以尝试使用开关并结束这样的事情:
function changeddl($this) {
var alertMsg;
switch($this.value){
case "New Posting":
alertMsg = "Please attach supporting document(s) below.";
break;
case "SpecialPay":
alertMsg = "Please attach supporting document(s) below.");
break;
case "DataEntry":
alertMsg = "Please attach supporting document(s) below.";
break;
case "CreditCardACHPosting":
alertMsg = "Please attach supporting document(s) below.";
break;
}
alert(alertMsg);
}
答案 1 :(得分:0)
我只想在您的选项上添加一个数据属性,并附上您想要的信息。
<select id="my_menu">
<option value="SpecialPay" data-alert-message="This is my message for Special Pay">Special Pay</option>
<option value="DataEntry" data-alert-message="This is my message for Data Entry">Data Entry</option>
</select>
然后是jQuery:
<script>
$(function(){
$('#my_menu').on('change', function(){
alert($('#my_menu option:selected').data('alert-message'));
});
});
</script>
如果您更喜欢打印内嵌消息而不是提醒,您可以随时在下拉菜单下方或上方添加元素,例如<p id="item_added"></p>
,而不是alert($('#my_menu option:selected').data('alert-message'));
,您可以执行以下操作:$('#item_added').text($('#my_menu option:selected').data('alert-message'));
答案 2 :(得分:0)
您可以将事件处理程序附加到select元素。例如,假设元素的id是“choices”。然后,您可以执行以下操作:
$('#choices').change(function() {
var selectedValue = $('#choices' + ' option:selected').attr('value');
switch (selectedValue)
{
case 'New Posting':
alert('Please attach supporting document(s) below.');
break;
case 'SpecialPay':
alert('Please attach supporting document(s) below.');
break;
case 'DataEntry':
alert('Please attach supporting document(s) below.');
break;
case 'CreditCardACHPosting':
alert('Verify CCD or Banking Information has been added.');
break;
}
});
事件处理函数执行以下操作:首先,它从下拉列表中获取当前所选选项的值HTML属性。然后,它使用switch语句显示相应的警报消息。