0

目的是从一个输入单元格中获取值并插入到另一个单元格中。

为了获得我使用的价值

var name = $('#test').val();

以上工作。

然后我需要插入。如果我插入简单文本(不是变量),那么它可以工作

$("#test3").val("Dolly Duck");

但是如何插入变量(var name)而不是 val(“Dolly Duck”)?

下面是整个代码

<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type="text/javascript">

//This works
$("#btn3").click(function(){
$("#test3").val("Dolly Duck");
});

//But his does not work
//at first get value from input form (define variable) and alert to check if it works
var name = $('#test').val();
//alert(name);

//now need to insert
//$("#btn4").click(function(){

//below does not work None of them
//$("#test").name;
//$("#test4").$('#test').val();
//$("#test4").jsvar: $('#test').val();

});
});
</script>
</head>
<body>
<p>Name: <input type="text" id="test" value="Mickey Mouse1"></p>
<p>Name: <input type="text" id="test3" value="Mickey Mouse2"></p>
<p>Name: <input type="text" id="test4" value="Mickey Mouse3"></p>
<button id="btn1">Show Value</button>
<button id="btn3">Set Value</button>
<button id="btn4">Set Value</button>
</body>
</html>
4

1 回答 1

2

传入变量:

$("#test3").val(name);

我还会在您要设置另一个文本框的值之前获取该值,因为该name变量不会自行更新:

$("#btn3").click(function() {
    var name = $('#test').val();
    $("#test3").val(name);
});

此外,请确保与 DOM 交互的代码位于$(document).ready()回调内部:

$(document).ready(function() {
    $("#btn3").click(function() {
        var name = $('#test').val();
        $("#test3").val(name);
    });
});
于 2013-04-14T07:02:41.267 回答