如何使用具有元素类型和 ID 的 jquery 选择器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7609345/
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
How to use jquery selector having element type and ID
提问by Manoj
I'm using this selector
$("textarea #myTextArea").val(text);
and it's not working. If I remove the ID and use the class it's working. Why isn't jquery able to find the element here?
我正在使用这个选择器
$("textarea #myTextArea").val(text);
,但它不起作用。如果我删除 ID 并使用它正在工作的类。为什么 jquery 不能在这里找到元素?
回答by Daniel A. White
Because of the space. With the space it says the #myTextArea
within a textarea
.
因为空间。随着空间,它说#myTextArea
在 a 内textarea
。
$("textarea#myTextArea").val(text);
回答by Clive
Just remove the space:
只需删除空格:
$("textarea#myTextArea").val(text);
At the moment you're trying to select an element with ID myTextArea
that is a descendant element of a textarea
目前,您正在尝试选择一个具有 ID 的元素,myTextArea
该元素是textarea
As Jared Farrish mentions in the comments removing the element type would be more efficient:
正如 Jared Farrish 在评论中提到的,删除元素类型会更有效:
$("#myTextArea").val(text);
If your document is valid then every ID will only used be once so this is still correct.
如果您的文件有效,那么每个 ID 只会使用一次,所以这仍然是正确的。