【发布时间】:2015-01-31 00:17:34
【问题描述】:
我过去曾问过类似的问题,但我整理了以下示例,以更好地说明我正在寻求的结果。
在经典 js 中使用唯一 id。(有效)
<style>
#par {width:350px; background:#DDD; padding:5px;}
#tatx {color:#C00;}
</style>
<div id="par">
Select an option, then, select another option<br>
<select id="sl" onChange="sltota();tatotx()">
<option value="item 1">option 1</option>
<option value="item 2">option 2</option>
<option value="item 3">option 3</option>
</select><br>
<p>Selected options values are passed to textarea<br>
<textarea id="ta" onChange="tatotx()"></textarea>
<p>Textarea value is passed to div as text
<div id="tatx">div text</div>
</div>
<script>
function sltota() {
slVal = document.getElementById('sl').value;
taVal = document.getElementById('ta').value;
document.getElementById('ta').value = taVal + ('- ') + slVal + ('\n');
}
function tatotx() {
taVal = document.getElementById('ta').value;
document.getElementById('tatx').innerHTML = taVal;
}
</script>
现在我正在尝试使用具有相同类的多个元素的 Jquery $(this) 修改此代码。但我不能让它工作,感谢任何帮助。(这不起作用)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<style>
li {margin-bottom:7px; background:#DDD; padding:5px;}
#par {width:350px;}
.tatx {color:#C00;}
</style>
<div id="par">
<ul>
<li>
Select an option, then, select another option.<br>
<select class="sl">
<option value="item 1">option 1</option>
<option value="item 2">option 2</option>
<option value="item 3">option 3</option>
</select><br>
<p>Selected options values are passed to textarea<br>
<textarea class="ta"></textarea>
<p>Textarea value is passed to div as text
<div class="tatx">Div Text</div>
</li>
<li>
Select an option, then, select another option.<br>
<select class="sl">
<option value="item 1">option 1</option>
<option value="item 2">option 2</option>
<option value="item 3">option 3</option>
</select><br>
<p>Selected options values are passed to textarea<br>
<textarea class="ta"></textarea>
<p>Textarea value is passed to div as text
<div class="tatx">Div Text</div>
</li>
<li>
Select an option, then, select another option.<br>
<select class="sl">
<option value="item 1">option 1</option>
<option value="item 2">option 2</option>
<option value="item 3">option 3</option>
</select><br>
<p>Selected options values are passed to textarea<br>
<textarea class="ta"></textarea>
<p>Textarea value is passed to div as text
<div class="tatx">Div Text</div>
</li>
</ul>
</div>
<script>
$(document).ready(function(){
$('li > .sl').on('change', function() {
$(this).sibling('.ta').val($(this).val());
$(this).sibling('.tatx').val($('.ta').val());
});
}
</script>
【问题讨论】:
-
好吧,1:变量名称有点混乱,