如何使用jQuery动态地使用.val()或.text()

How to distiguish when to use .val() or .text() dynamically using jQuery?

本文关键字:val text 何使用 jQuery 动态      更新时间:2023-09-26

我需要能够知道何时使用val()以及何时将text()与jQuery一起使用。

如果我有一个具有相同类名的spaninput,我需要在输入上应用val(),在跨度上应用text()以设置其值/内容。

这是我的 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

https://jsfiddle.net/gqxsdsyb/5/

试试 .is() 函数。你可以用它进行元素检测。例如

if ($(element).is("span")){/* set text */}
// or
if ($(element).is("input")){/* set val */}