option触发事件两种方法总结

时间:2023-03-09 22:01:34
option触发事件两种方法总结

代码如下:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>option触发事件</title>
<script src="jquery-1.7.2.min.js"></script>
</head>
<body>
<select name="" id="selected">
<option value="1001">option1</option>
<option value="1002">option2</option>
<option value="1003">option3</option>
<option value="1004">option4</option>
<option value="1005">option5</option>
</select>
<div id="test">
<dd class="sheng">您所在省:</dd>
<dd><input type="text" class="input1" placeholder="浙江省"></dd>
</div>
</body>
<script>
$(document).ready(function(){
/*
* 方法一
$("#selected").on("change",function(){
if ($("option:selected",this).index() ==0) {
$(".sheng").html("您所在省:");
$(".input1").attr("placeholder","请输入您所在省");
};
if ($("option:selected",this).index() ==1) {
$(".sheng").html("您所在市:");
$(".input1").attr("placeholder","请输入您所在市");
};
if ($("option:selected",this).index() ==2) {
$(".sheng").html("您的爱好:");
$(".input1").attr("placeholder","请输入您的爱好");
};
if ($("option:selected",this).index() ==3) {
$(".sheng").html("您的性别:");
$(".input1").attr("placeholder","请输入您的性别");
};
if ($("option:selected",this).index() ==4) {
$(".sheng").html("您最喜欢的水果:");
$(".input1").attr("placeholder","请输入您最喜欢的水果");
};
});
*/ /*方法二*/
$("#selected").on("change",function(){
if ($("option:selected",this).val() == '1001') {
$(".sheng").html("您最喜欢的水果:");
$(".input1").attr("placeholder",'请输入您最喜欢的水果');
}
else if ($("option:selected",this).val() == '1002') {
$(".sheng").html("您的性别:");
$(".input1").attr("placeholder",'请输入您的性别');
}
else if ($("option:selected",this).val() == '1003') {
$(".sheng").html("您的爱好:");
$(".input1").attr("placeholder",'请输入您的爱好');
}
else if ($("option:selected",this).val() == '1004') {
$(".sheng").html("您所在市:");
$(".input1").attr("placeholder",'请输入您所在市');
}
else{
$(".sheng").html("您所在省:");
$(".input1").attr("placeholder",'请输入您所在省');
}
});
});
</script>
</html>

总结:

1、要使用jquery库,务必要引用 jquery-1.7.2.min.js 文件

2、option 触发 click事件,首先要给 select 加 onchange 事件,因为option 不能直接触发click事件

3、if 判断option选项值时,务必要 使用 $("option:selected",this),后面用索引值index()或val()根据自己的喜好吧

作为前端菜鸟,还是要多敲代码,加油!多自己主动思考,没有思路多百度,如果还是解决不了的话,就请教比自己厉害的,善于总结,希望可以帮到需要的人。

相关文章