此代码在焦点上创建动态文本框到最后一个文本框,所有文本框中的值为0,我想在动态创建的文本框中添加动态值
<html>
<head>
<script> src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
<script>
$(document).ready(function(){
$( "input" ).on('focus' , addNew);
function addNew (){
if($(this).is(':last')){
$( this ).after( '<input type="text" value="0"/>' );
$( "input" ).on('focus' , addNew);
}
}
});
</script>
</head>
<body>
<script>
var divBox1 = document.createElement("div");
divBox1.style.height = "100%";
divBox1.style.width = "200px";
document.body.appendChild(divBox1)
var input = document.createElement('input');
divBox1.appendChild(input);
</script>
</body>
</html>
答案 0 :(得分:0)
这里几乎没有问题:
<script>src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
应该是
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> </script>
您确定目标input
是否为last
的方式不合适。请查看以下更新的代码段。
var divBox1 = document.createElement("div");
divBox1.className = "ipHolder";
//adding a class to identify the container of input elements
divBox1.style.height = "100%";
divBox1.style.width = "200px";
document.body.appendChild(divBox1)
var input = document.createElement('input');
divBox1.appendChild(input);
$(document).ready(function() {
$("input").on('focus', addNew);
function addNew() {
var isLast = $(this).closest('.ipHolder').find('input').length - ($(this).index() + 1) == 0;
//subtract the number of inputs present already with the index of clicked input
//within in the container for inputs and see if it is 0 which means its the last element
if (isLast) {
$(this).after('<input type="text" value="0"/>');
$("input").on('focus', addNew);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>