【问题标题】:JQuery .find() can find by id, but not by classJQuery .find() 可以按 id 查找,但不能按类查找
【发布时间】:2018-06-24 03:54:03
【问题描述】:

我使用 Jquery 创建了以下 DOM:

<div id="d0" class="choiceDiv">
    <input type="checkbox" id="cb0" class=".userCheckBox" value="Option 1" checked="checked">
    <input type="hidden" id="h0" class=".userCheckBoxHidden" value="true">
    <label for="cb0">Option 1</label>
</div>

我已将 CSS 标记应用于 DOM 中的元素,通过 CSS 类,此时它们内部没有任何属性。

一个 div 中大约有 17 个。加载页面后,我想重新加载每个复选框的当前选中值。当我遍历每个代码时,我尝试在 DOM 上使用 .find() 函数:

$('.choiceDiv').each(function(e){

当我尝试按类查找时,

$(this).find('.userCheckBox');

我得到以下失败对象:

init [prevObject: init(1), context: div#d0.choiceDiv, selector: ".userCheckBox"]
context: div#d0.choiceDiv
length: 0
prevObject:init [div#d0.choiceDiv, context: div#d0.choiceDiv]
selector:".userCheckBox"
__proto__:Object(0)

当我尝试通过 ID 查找时,

$(this).find('#cb'+e)[0];

我得到了我正在寻找的东西:

<input type="checkbox" id="cb0" class=".userCheckBox" value="Option 1" checked="checked">

我希望按类提取对象,以确保始终获得我正在寻找的输入类型。有人可以解释为什么在这种情况下我可以使用带有 ID 而不是 Class 的 .find() 吗?我尝试使用 this post 解决它,但无法让它工作。

【问题讨论】:

  • class=".userCheckBox" 关闭 .。选择器使用它来表示一个类。它不会出现在您的实际标记中。就像您没有在 id="" 中添加 # 一样

标签: javascript jquery css


【解决方案1】:

只需从类属性中删除句点即可。例如:

&lt;input type="checkbox" id="cb0" class="userCheckBox" value="Option 1" checked="checked"&gt;

可以通过.find('.userCheckBox').find('#cb0') 找到。

【讨论】:

  • 非常感谢,Cameron 和 Teplar!希望我的眼睛不要那么斜视!
猜你喜欢
  • 2018-02-09
  • 2011-06-23
  • 2016-05-18
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-21
相关资源
最近更新 更多