这个问题在这里已有答案:
我是jQuery
的新手,非常感谢你的帮助。
我正在努力与jQuery DOM
操纵,我有一个<input>
,和.on("blur")
它更新DOM
,通过删除<input>
,并插入<div>
与<input>
值,当你点击<div>
,它必须更新DOM
,通过将<input>
与<div>
的值相加回来。
当我点击<div>
时,没有任何反应。有任何想法吗?
我目前的代码:
$(document).ready(function() {
var inputValueByClassName = null;
$(".divInput").on("click", function() {
alert("clicked!")
$(".divInput").replaceWith($('<input type="text" class="textInput>'));
$(".divInput").html(inputValueByClassName);
});
$(".textInput").on("blur", function() {
inputValueByClassName = $('input[type="text"].textInput').val();
console.log(inputValueByClassName);
$(".textInput").replaceWith($('<div class="divInput">' + inputValueByClassName + '</div>'));
})
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="textInput" value="123"><br>
您错过了输入中关闭class="textInput"
。对于动态标签,请使用$(document).on("click",
$(document).ready(function() {
var inputValueByClassName = null;
$(document).on("click",'.divInput',function(){
$(this).replaceWith($('<input type="text" class="textInput" value="'+$(this).text()+'">'));
});
$(document).on("blur",'.textInput' ,function(){
var inputValueByClassName = $(this).val();
$(this).replaceWith($('<div class="divInput">' + inputValueByClassName + '</div>'));
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input type="text" class="textInput" value="123"><br>
</body>
那是因为你的on('click')
函数只为当前在页面上的元素注册(页面加载时没有)。如果稍后插入元素(就像模糊输入元素时那样),clickhandler不会自动绑定到动态插入的div。
您可以使用像$(document).on("click", ".divInput" , function() { });
这样的事件委派
然后,您将单击绑定到整个文档,并在单击具有类divInput的元素时作出反应,否则它不会执行任何操作。
请记住,这不是很高效,尝试将$(文档)中的区域缩小为类似于$('.input-area').on('click', '.divInput', function() {});
的区域,其中输入区域只是围绕着您的输入
你在页面加载时调用$(".divInput").on("click", function() {})
,此时你的div还不存在。
您可以使用$.on('click', '.divInput', function() {});
来侦听任何具有divInput类的元素,该类在任何点(即使将来)添加到dom树中。
和$.on('blur', '.textInput', function() {});
的输入。
但我建议您同时存在这两个元素,并显示show()或hide()。