2010-11-04 28 views
1

在下面的javascript,可變臨時將舉行HTML字符串這樣,jquery屬性操作(DOM操作)輸入類型文本不工作?

<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> 

回答

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">" 
}); 
+0

@ user443095 - 這取決於瀏覽器,究竟發生了什麼渲染,但認爲它是這樣的,HTML是瀏覽器用來創建DOM的東西,在這之後它們並沒有像(1:1)那麼強大的連接,DOM可以通過很多方式進行操作,而在html輸出中不會看到DOM。 – 2010-11-04 22:40:24

+0

好,DOM和HTML不一樣。 但我不明白這一點,如果我已經使用了這將導致在html和dom中修改'value'屬性。現在爲什麼這適用於隱藏類型但不是文本類型? – Aman 2010-11-04 22:47:37

+0

@Nikc,我看到ok .. thanx很多Nick,幫了很多 – Aman 2010-11-04 22:49:32