javascript - 如何使用 jQuery 动态区分何时使用 .val() 或 .text()?

标签 javascript jquery html

我需要知道何时对 jQuery 动态使用 val() 以及何时使用 text()

如果我有一个具有相同类名的 spaninput,我需要在输入上应用 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

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

关于javascript - 如何使用 jQuery 动态区分何时使用 .val() 或 .text()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34936524/

相关文章:

javascript - Jquery:替换图像源从 anchor 标记获取链接

html - CSS - 三个可滚动的等高主要内容列(流体高度)和粘性/始终可见的页脚

javascript - 当按钮类更改时,jQuery 调用不同的函数

javascript - JQuery/Javascript - 如何通过表头文本查找表头的索引

jquery - 如何在 ASP.NET MVC 中返回 JSON 格式的 500 错误?

javascript - 默认关闭标签

javascript - 如何使用 Javascript 从 JSON 文件中选择一个随机对象(?)?

javascript - 咕噜声 : Phaser isn't Defined

javascript - 反转存储在 javascript 变量中的 JSON 数组

html - div 不跨越页面宽度