嗨,我正在尝试使用jquery自动更新围绕contenteditable div包裹的输入字段。后端代码生成了多个这样的div,我希望每个输入仅在其父级的div的contenteditable已更新时才进行更新。html看起来像这样:
<div class="to-change" contenteditable="true">
Text that can be edited
<input name="autoupdate">
</div>
我尝试使用以下jQuery代码:
<script>
$( document ).ready(function() {
console.log( "ready!" );
$('.to-change').on("keyup", function() {
var input = $(this).text()
$('input:first-child').val(input)
})
});
</script>
问题是,当我尝试更改文本时,所有其他此类div的输入字段也将使用相同的文本进行更新。如何更改jquery代码,以使输入字段始终引用其父div的引用?
谢谢!
您可以这样选择该元素:
$(document).ready(function () {
console.log("ready!");
$('.to-change').on("keyup", function () {
var input = $(this).text()
$('.to-change > :first-child').val(input);
});
})
要么:
$(document).ready(function () {
console.log("ready!");
$('.to-change').on("keyup", function () {
var input = $(this).text()
$('.to-change > input').val(input);
});
})
“>”用于选择元素的直接子元素,您可以在https://developer.mozilla.org/zh-CN/docs/Web/CSS/Child_combinator中找到有关此选择器的更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句