简体   繁体   English

如何从jQuery选择器访问javascript方法

[英]How can I access javascript methods from jQuery selectors

I have this plain js: 我有这个简单的js:

var innerText  = document.getElementById("TaskId").options[0].text;

And I was wondering how to convert it to jQuery: 我想知道如何将其转换为jQuery:

var innerS = $("#TaskId");
var innerText = innerS.options[0].text;

This throws an error: 这会引发错误:

innerS.options is undefined

EDIT 编辑

In accordance with some of the debate I threw a quick speed test together: 根据一些辩论,我一起快速测试:

js: JS:

var startDat = Date.now();
for (var c = 0; c < 100000; c++) {
    var com = $("#TaskId").get(0);
}
var endDat = Date.now();
alert("jQ.get(0) took " + (endDat - startDat) + "ms");


var startD = Date.now();
for (var co = 0; co < 100000; co++) {
    var com = $("#TaskId")[0];
}
var endD = Date.now();
alert("jQ[0] took " + (endD - startD) + "ms");

var startDa = Date.now();
for (var comp = 0; comp < 100000; comp++) {
    var compa = document.getElementById("TaskId");
}
var endDa = Date.now();
alert("js took " + (endDa - startDa) + "ms");

results: 结果:

jQ.get(0) took 1042ms
jQ[0] took 1057ms
js took 136ms

A jQuery object contains an array of DOM elements. jQuery对象包含DOM元素数组。 If you want direct access to the DOM elements, there are a number of ways to get that direct access. 如果您想直接访问DOM元素,可以通过多种方式获得直接访问权限。 For example, you can directly get the first DOM element with this: 例如,您可以使用以下方法直接获取第一个DOM元素:

var innerS = $("#TaskId").get(0);

Now innerS is the actual DOM element and not a jQuery object any more. 现在innerS是实际的DOM元素,而不再是jQuery对象。

For fastest execution time, use: 为了最快的执行时间,请使用:

var innerS = document.getElementById("TaskId");

jQuery can be fast to code with, but is not always the fastest for execution time as jQuery objects carry some overhead with them (constructing them, sorting DOM elements, etc...). jQuery可以快速编写代码,但并不总是执行时间最快,因为jQuery对象带有一些开销(构造它们,排序DOM元素等等)。

You can get the entire DOM array like this: 您可以像这样获取整个DOM数组:

var optionElements = $("option").get();

Of course, one of the reasons for using jQuery objects is that they have a set of cross-browser methods that make it easy to just use their methods instead of the direct DOM methods in some cases. 当然,使用jQuery对象的原因之一是它们有一组跨浏览器方法,这使得在某些情况下使用它们的方法而不是直接DOM方法变得容易。 In your particular case, you could get the innerText like this: 在您的特定情况下,您可以像这样获取innerText:

var text = $("#TaskId").text();

A jQuery object is essentially just a wrapper around a DOM element so in order to access the DOM element itself you can use either .get(0) or [0]: jQuery对象本质上只是DOM元素的包装器,因此为了访问DOM元素本身,您可以使用.get(0)或[0]:

$('#TaskId').get(0).options[0].text;

// OR

$('#TaskId')[0].options[0].text;

Two possible solutions: 两种可能的解决方

var innerText = innerS[0].options[0].text; 
// Are you sure about .text? I never used it.

or 要么

var innerText = $("#TaskId option:first").text();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM