在輸入內容中輸入內容並點擊按鈕後,「.val()」返回一個空值,爲什麼?jQuery.val()在<input>標記上不起作用
HTML代碼:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
<div class="class3" >
<div class="class4">
<h3>Settings 2</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
<label>
<span>Text 2:</span>
<input type="text" name="text2">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
JavaScript代碼:
$('#Go').on('click', function() {
alert($('.class1 input').val()); //return an empty value
$('.class1 input').val("test");
alert($('.class1 input').val()); //return test
});
編輯:
即使這並不工作,這裏我只是一個輸入,所以我不能鍵入錯誤的:
<div class="mainClass">
<div class="class1" >
<div class="class2">
<h3>Settings 1</h3>
<label>
<span>Text 1:</span>
<input type="text" name="text">
</label>
</div>
</div>
</div>
<button id="Go" class="go" >GO </button>
編輯2:我發現這個問題的一個開始......
當我這樣做:
$('.class1 input').each(function() {
alert($(this).attr('name') + " value:" +$(this).val());
});
我得到兩個「警告」是這樣的:
text value:
text value:myinputText
於是兩個創建在我的HTML中,第一個是空的,第二個很好用! 仔細看我的網頁,我發現所有元素都是重複的(<select,field, input...
)
任何想法怎麼可能?我打電話兩次我的HTML文件? 我所有的代碼是在一個彈出(我不知道它是否能夠幫助) (我在Javascript和jQuery新)
感謝
''不是標籤.. –
@dystroy爲什麼不應該這樣呢?我很確定這是完全有效的,並接受這樣做 – Ian
@dystroy這裏有一個參考:http://stackoverflow.com/questions/774054/should-i-put-input-tag-inside-label-tag – Ian