jQuery 对象到 JavaScript 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5533773/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery object to JavaScript object
提问by Alex
If I have a textarea
like var txtarea = $('textarea')
, how can I set the value to it using the JavaScript property value
, and not the jQuery property val()
?
如果我有一个textarea
赞var txtarea = $('textarea')
,我如何使用 JavaScript 属性value
而不是 jQuery 属性为其设置值val()
?
I think I need to convert txtarea
to a JavaScript object, but how do I?
我想我需要转换txtarea
为 JavaScript 对象,但我该怎么做?
回答by karim79
回答by nonopolarity
The jQuery .get()
will do that for you
jQuery.get()
会为你做到这一点
Quoted:
引:
Without a parameter,
.get()
returns all of the elements:alert($('li').get());
With an index specified,
.get()
will retrieve a single element:($('li').get(0));
...we can use the array dereferencing operator to get at the list item instead:
alert($('li')[0]);
没有参数,
.get()
返回所有元素:alert($('li').get());
指定索引后,
.get()
将检索单个元素:($('li').get(0));
...我们可以使用数组解引用运算符来获取列表项:
alert($('li')[0]);
回答by SLaks
jQuery objects areJavascript objects.
jQuery 对象是Javascript 对象。
You're trying to learn about the world of pain known as raw DOM scripting.
您正在尝试了解被称为原始 DOM 脚本的痛苦世界。
You can write
你可以写
document.getElementsByTagName("textarea")[0].value = whatever;
This will get the first <textarea>
and set its value.
If you want to set values for all of them, you'll need a loop.
这将获得第一个<textarea>
并设置其值。
如果您想为所有这些设置值,您将需要一个循环。
You can also get a raw DOM element out of a jQuery object by writing $(whatever)[0]
.
您还可以通过编写$(whatever)[0]
.
回答by mVChr
You can pull the HTMLElement using array notation:
您可以使用数组表示法提取 HTMLElement:
$('textarea')[0].value
...will get the value of the first element in the $('textarea')
jQuery list.
...将获得$('textarea')
jQuery 列表中第一个元素的值。
回答by Abhishek Srivastava
We can use javascript's querySelector()
function to get a standard javascript DOM object.
我们可以使用 javascript 的querySelector()
函数来获取一个标准的 javascript DOM 对象。
Example :
例子 :
<ul id="category"><li><label><input data-id="1" data-label="CBSE" data-filterClass="category" name="category" type="checkbox"> CBSE </label></li>
console.log(document.querySelector('input[data-id="1"]'));
You will get javascript DOM object for given selector.
您将获得给定选择器的 javascript DOM 对象。