我正在尝试输入两个不同的文本框,并在按钮上单击交换文本
可悲的是,一切都没有发生。我错过了一些超级简单的东西吗?<input type="text" id="string1" class="str_1 inputs" value="type something pointless"/>
<input type="button" onClick="switchITup();" id="theButton" value="do something amazing">
<input type="text" id="string2" class="str_2 inputs" value="type something meaningful"/>
function switchITup(){
var val1 = $('#string1').val;
var val2 = $('#string2').val;
$('#string1').text(val2);
$('#string2').text(val1);
$('#string1').removeClass('inputs');
$('#string1').addClass('YooHoo');
};
Codepen here。
答案 0 :(得分:2)
在您的代码中(val
需要val()
而text()
需要val()
): -
function switchITup(){
var val1 = $('#string1').val();
var val2 = $('#string2').val();
$('#string1').val(val2);
$('#string2').val(val1);
$('#string1').removeClass('inputs');
$('#string1').addClass('YooHoo');
};
.inputs{
font-size:20px;
}
.YooHoo{
font-size:12px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="string1" class="str_1 inputs" value="type something pointless"/>
<input type="button" onClick="switchITup();" id="theButton" value="do something amazing">
<input type="text" id="string2" class="str_2 inputs" value="type something meaningful"/>
注意: - 添加了一些样式以向您显示它工作正常
答案 1 :(得分:1)
我认为它应该是.val
而不是Lorem Ipsum
<div class="this-parent-div-is-necessary">
<div class="div-sticky-class">
Test
</div>
<div>Lorem ...</div>
<div>Lorem ...</div>
<div>Lorem ...</div>
<div>Lorem ...</div>
<div>
<p>It will works here too</p>
</div>
</div>
Won't work here because it's outside the parent of div-sticky-class
<br/><br/><br/><br/><br/><br/><br/><br/><br/>
答案 2 :(得分:0)
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("input:text").val("new value");
});
});
</script>
</head>
<body>
<p>Name: <input type="text" name="user"></p>
<button>Set the value of the input field</button>
</body>
</html>