用于输入类型文本的jquery属性操作(DOM操作)不起作用?

时间:2010-11-04 06:23:10

标签: jquery

在下面的javascript中,变量 temp 会保存这样的html字符串,

<input type="text" value="initial text" name="msg" />

为什么这段代码

$('input[name=msg]').val('hello world');

不会将html字符串更改为

<input type="text" value="hello world" name="msg" />    

这是代码,

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<form><input type="text" value="initial text" name="msg" /></form>

<script type="text/javascript">
    $().ready(function(){
        $('input[name=msg]').val('hello world');

        var temp = $('form').html();

        console.debug(temp);        
    });
</script>
</body>
</html>

更新

<form>
    <input type="hidden" value="foo" name="msg1" />
    <input type="text" value="bar" name="msg2" />
</form>

<script type="text/javascript">
    $(function(){
        $('input[name=msg1]').val('hello world 1'); // this manipulates dom at html level
        $('input[name=msg2]').val('hello world 2'); // this does not! why?

        $('form').html();
    });
</script>

1 个答案:

答案 0 :(得分:2)

元素的HTML与其DOM属性不同,就是它的样子。虽然您的.ready()样式已被弃用,但这不是问题。如果这样做,您将看到正确的值:

console.debug($('input[name=msg]').val()); //"hello world"
console.debug($('form').serialize()); //"msg=hello+world"

You can test it here

$(function() {
  $('input[name=msg]').val('hello world');
  var temp = $('form').html();

  console.debug($('input[name=msg]').val()); //"hello world"
  console.debug($('form').serialize());      //"msg=hello+world"
  console.debug(temp);                       //"<input type="text" value="initial text" name="msg">"
});