我有一个表,要在其中提取活动项的文本。我使用以下代码执行此操作:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
问题是我一直不确定。我检查了控制台,它确实找到了我想要的元素。
我对Java语言还比较陌生,但是经过一个多小时的Google搜索后,我找不到问题了,我也不明白为什么。我知道,如果使用以下代码对文本元素进行硬核化,就可以得到该文本元素:
document.querySelector("#selectiona1").textContent
但不包含:
$("#selectiona1").textContent
这2个有什么区别?我读到textContent是DOM的一部分,据我了解它与对象有关,根据我的控制台,我认为它是对象。我做了一些疯狂的尝试,例如将我放入的对象放入querySelector中,但是没有任何效果。
答案 0 :(得分:1)
此行:
allow read : if resource.data.uid == request.auth.uid;
您正在使用 jQuery 在var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
中选择.dropdown-item.active
,当您使用jQuery选择时,会得到一个jQuery对象作为响应。因此,#custDropDownMenuA
是一个jQuery对象,并且jQuery对象通常不具有与标准HTMLElements相同的属性/方法。 (addedWorkout
是检索元素的原始Javascript方法)
在jQuery集合中选择第querySelector
条,以获取第一个匹配元素:
[0]
或者使用jQuery方法获取第一个匹配元素的文本,即var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
:
.text()
(请注意使用新变量-在可能的情况下,创建新变量比重新分配旧变量更容易阅读和调试代码)
答案 1 :(得分:1)
您的var 'addedWorkout'
是一个Jquery对象,而不是html元素。
要显示文字,请使用:
addedWorkout.text();
或者,您可以通过添加索引[0]将'addedWorkout'
更改为html元素,如下所示:
addedWorkout[0].textContent;