我需要知道何时对 jQuery 动态使用 val()
以及何时使用 text()
。
如果我有一个具有相同类名的 span
和 input
,我需要在输入上应用 val()
和 text()
在 span 上设置它的值/内容。
这是我的 HTML 标记
<input class="att" name="some1" value="" type="text"><br>
<input class="att" name="some2" value="" type="text"><br>
<input class="att" name="some3" value="" type="text"><br>
<div class="att"></div><br>
<div id="test" class="att"></div><br><br>
<div id="cl">Click Me</div>
这是我尝试过的,但没有按预期设置值
$(function(e){
$('#cl').click(function(e){
//Select any input that has the class "att" and apply the val() function
$('.att :input').val('123');
//Select any element that is not an input and apply the text() function
$('.att').not(':input').text('123');
//Search for an element with a known ID but apply `val()` if the element is input
$('#text .att :input').val('123');
//Search for an element with a known ID but apply `text()` if the element is not an input
$('#text .att').not(':input').text('123');
});
});
我还创建了一个jfiddle用我的代码
如何根据元素类型正确应用 val() 和文本?
最佳答案
您使用了错误的选择器。这就是为什么你没有得到想要的结果。当您需要在选择器内部搜索更多元素时,请在选择器之间使用空格,否则不要使用它们。
应该是.att:input
和
#text.att:input
和
#text.att
关于javascript - 如何使用 jQuery 动态区分何时使用 .val() 或 .text()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936524/