我要做的就是将我在标签上写的内容复制到另一个标签上,但是什么也没有发生。我希望将在主输入上键入的内容复制到label1输入。预先感谢
<head>
<body>
<title>form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div class='form' width='100%' height='100%'>
<input id='mainId' type="text" name="main" value="" width="100px">main</input>
<br>
<input id='1' type="text" name="label1" value="" width="20px">label1</input>
</div>
<button>Click</button>
</body>
<script>
var change;
setTimeout(function() {
change = document.getElementById('mainId').value;
}, 1);
$("button").click(function(){
$("#1").attr("value", change);
});
</script>
</head>
答案 0 :(得分:2)
让我们从修复HTML开始,这在您的代码中确实是有问题的。
<script>
,<title>
之类的标签以及其他标签应放在<head>
内,而不是正文。<head>
应该在<body>
之前。<input>
是一个自动关闭的标签,它不能包含文本或其他元素,应为.../>main
而不是...>main</input>
说,现在我们可以解决Javascript问题:
change
,也不需要计时器。#mainId
)获得.val(),并将其设置为第二个输入(value
)的#1
。
请参见下面的代码。
为您提供的提示:阅读文档,以了解更多有关HTML的语义以及JS和jQuery中的方法。
使用 HTML验证器,例如this one
$("button").click(function() {
let changedTxt = $("#mainId").val()
$("#1").val(changedTxt)
});
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<title>form</title>
</head>
<body>
<div class='form' width='100%' height='100%'>
<input id='mainId' type="text" name="main" value="" width="100px" />main
<br>
<input id='1' type="text" name="label1" value="" width="20px" />label1
</div>
<button>Click</button>
</body>