如何在以下HTML用例中找到下一个文本区域?
小提琴:https://jsfiddle.net/hthaava8/
jQuery:代码:
$("textarea").keyup(function (e) {
var txtArea = $(this).next().find('textarea').eq(0);
alert(txtArea.attr('id'));
$(txtArea).focus();
$(txtArea).val("nicetried");
});
HTML代码:
<div class="pure-u-1 pure-u-md-1-8">
<div class="pure-g">
<div class="pure-u-1-2 ">
<p class="boldText">2.1 </p>
</div>
<div class="pure-u-1-2">
</div>
</div>
</div>
<div class="pure-u-1 pure-u-md-2-5">
<p class="boldText">focus to next textarea?</p>
</div>
<div class="pure-u-1 pure-u-md-1-5">
<textarea class="" id="commenty" style="height: 89px; overflow-y: hidden;"></textarea>
</div>
<div class="pure-u-1 pure-u-md-1-8">
<div class="pure-g">
<div class="pure-u-1-2 ">
<p class="boldText">2.2 </p>
</div>
<div class="pure-u-1-2">
</div>
</div>
</div>
<div class="pure-u-1 pure-u-md-2-5">
<p class="boldText">focus to next textarea?</p>
</div>
<div class="pure-u-1 pure-u-md-1-5">
<textarea class="" id="commenty1" style="height: 89px; overflow-y: hidden;"></textarea>
</div>
<div class="pure-u-1 pure-u-md-1-8">
<div class="pure-g">
<div class="pure-u-1-2 ">
<p class="boldText">2.3 </p>
</div>
<div class="pure-u-1-2">
</div>
</div>
</div>
<div class="pure-u-1 pure-u-md-2-5">
<p class="boldText">focus to next textarea?</p>
</div>
<div class="pure-u-1 pure-u-md-1-5">
<textarea class="" id="commenty2" style="height: 89px; overflow-y: hidden;"></textarea>
</div>
答案 0 :(得分:4)
您可以使用
$(this) // Current textarea
.parent() // Get parent
.nextAll('.pure-u-md-1-5') // Get all instance of textarea next to current element
.first() // Get first instance
.find('textarea') // Select textarea element inside that
.focus().val("nicetried"); // Focus and set value
不使用课程:
您可以使用:has()
选择器。
$(this)
.parent()
.nextAll('div:has(textarea)').first() // Select `div` having textarea and get first
.find('textarea')
.focus().val("nicetried");