jquery中有多少参数,以下示例我如何使用this
我有两个选择框,如果我更改了我的选择1的值,则它们都是相同的另一个选择也一直在刺激,这是不应该的,这就是为什么我想要阻止这个我怎么能那样做?
$(document).ready(function() {
$(".person-1, .person-2").change(function() {
var val1 = parseInt($('.person-1').find(":selected").text()),
val2 = parseInt($('.person-2').find(":selected").text());
$(".addition-1").text(val1);
$(".addition-2").text(val2);
$(".addition").text(val1 + val2);
});
});

select {
width: 150px;
height: 40px;
}
.personBox {
background: #FFF;
width: 350px;
border: 1px solid #ccc;
padding: 10px;
float: left;
margin-right: 10px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="personBox">
<h2>SELECT 1</h2>
<select class="person-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="person-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p>Add 1: <span class="addition-1"></span></p>
<p>Add 2: <span class="addition-2"></span></p>
<p>Addition : <span class="addition"></span> </p>
</div>
<!-- personBox-->
<div class="personBox">
<h2>SELECT 2</h2>
<select class="person-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="person-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p>Add 1: <span class="addition-1"></span></p>
<p>Add 2: <span class="addition-2"></span></p>
<p>Addition : <span class="addition"></span> </p>
</div>
<!-- personBox-->
&#13;
答案 0 :(得分:5)
您必须提供一个上下文,以查找元素在文档中找不到元素。
$(document).ready(function() {
$(".person-1, .person-2").change(function() {
var context=$(this).closest('div');
var val1 = parseInt($('.person-1',context).find(":selected").text()),
val2 = parseInt($('.person-2',context).find(":selected").text());
$(".addition-1",context).text(val1);
$(".addition-2",context).text(val2);
$(".addition",context).text(val1 + val2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="personBox">
<h2>SELECT 1</h2>
<select class="person-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="person-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p>Add 1: <span class="addition-1"></span></p>
<p>Add 2: <span class="addition-2"></span></p>
<p>Addition : <span class="addition"></span> </p>
</div>
<!-- personBox-->
<div class="personBox">
<h2>SELECT 2</h2>
<select class="person-1">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="person-2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<p>Add 1: <span class="addition-1"></span></p>
<p>Add 2: <span class="addition-2"></span></p>
<p>Addition : <span class="addition"></span> </p>
</div>
<!-- personBox-->