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()根據自己的喜好吧

 

作為前端菜鳥,還是要多敲代碼,加油!多自己主動思考,沒有思路多百度,如果還是解決不了的話,就請教比自己厲害的,善於總結,希望可以幫到需要的人。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM