假设我有两个id为“name”和“address”的字段。我想向用户显示div消息中的实际值。我做了
<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div style="visibility:hidden">
<div>Your name is $(name)</div>
<div>Your address is $(address)</div>
</div>
我试过
<div style="visibility:hidden">
<div>Your name is <script>$("input[id=name]").val()</script></div>
<div>Your address is <script>$("input[id=address]").val())</script></div>
</div>
我的名字和地址都是空的。
Questtion是如何解决它的,有没有更好的方法?像
<div style="visibility:hidden">
<div>Your name is <script>GetValue(name)</script></div>
<div>Your address is <script>GetValue(address)</</script></div>
</div>
并使用jquery替换值?
答案 0 :(得分:1)
试试这个:
<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div style="visibility:hidden">
<div>Your name is <span id="userName"></span></div>
<div>Your address is <span id="userAddress"></span></div>
</div>
<script type="text/javascript">
$(function(){
$("#userName").text($("#name").val());
$("#userAddress").text($("#address").val());
});
</script>
答案 1 :(得分:1)
.val()
返回值,但不会将其写入DOM。您可以使用document.write
:
<div style="visibility:hidden">
<div>Your name is <script>document.write($("input[id=name]").val());</script></div>
<div>Your address is <script>document.write($("input[id=address]").val());</script></div>
</div>
但是,更好的方法更多的是
<div style="visibility:hidden">
<div id="name-div"></div>
<div id="address-div"></div>
</div>
<script>
$("#name-div").text("Your name is " + $("#name").val());
$("#address-div").text("Your address is " + $("#address").val());
</script>
答案 2 :(得分:0)
我在这里创建了一个jsfiddle:http://jsfiddle.net/7se87/
$("input").keyup(function () {
var spanclass = $(this).attr('id');
var value = $(this).val();
$("span."+spanclass).text(value);
}).keyup();
<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div style="display:block;">
<div>Your name is <span class='name'></span></div>
<div>Your address is <span class='address'></span></div>
</div>
答案 3 :(得分:0)
给出两个结果div id,以及封闭(隐藏)div:
<input type="text" id="name" value="MyName" />
<input type="text" id="address" value="myaddress" />
<div id="result" style="visibility:hidden">
<div id="result_name"></div>
<div id="result_address"></div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#name').change(function() {
jQuery('#result_name').text('Your name is ' + jQuery(this).val());
});
jQuery('#address').change(function() {
jQuery('#result_address').text('Your address is ' + jQuery(this).val());
});
jQuery('#result').css('display', 'block');
});
</script>