假设我有一个名为 unitTables
的表,其中包含一些行。它是网页上许多类似表格之一。在这些行中有一个名为 selected
的类,我想检索该类以获取变量。页面上的其他表也使用 selected
类,因此我需要检索 selected
的这个特定实例。
在纯 JavaScript 中,找到它的方法是:
var table = document.getElementById('unitTables');
var selected = table.getElementsByClassName("selected");
上面两行在 jQuery 中相当于什么?
我知道我可以像这样重写第一行:
var table = $('#unitTables');
但我知道我不能对下一行执行完全相同的操作,因为我需要使用 unitTables
的 id 才能获取特定的选择
该表中的行。目前我有:
var selected = from.$(".selected");
这会引发 Uncaught TypeError: from.$ is not a function.
错误,所以我知道这不是正确的语法。
最好的方法是什么?
最佳答案
var table = document.getElementById('unitTables'); var selected = table.getElementsByClassName("selected");
What's the equivalent to the above two rows in jQuery?
var selected = $("#unitTables .selected");
(除了 selected
将是匹配元素集周围的 jQuery 对象,而不是集合。)
jQuery function (jQuery
或 [通常] $
)通过 CSS selectors 查找元素。因此,在本例中,后代选择器在 #unitTables
中查找 .selected
。
关于javascript - jQuery:如何获取另一个元素内某个元素的类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45487083/