简体   繁体   English

在jQuery中选择具有特定ID的特定元素类型

[英]Select specific element type with specific ID in jQuery

I want to find any canvas elements with the id whatever using jQuery. 我想找到任何canvas与ID元素whatever使用jQuery。 I thought I could do $('canvas #whatever') but that doesn't return anything when I have a canvas with that id on the page. 我以为我可以做$('canvas #whatever')但是当我在页面上有一个带有该id的画布时,它不会返回任何内容。

Your selector will return an element that is a canvas's child. 您的选择器将返回一个画布的子元素。 Doing $('#whatever') should already return what you expect, since IDs should be unique in a page. 执行$('#whatever')应该已经返回了您期望的内容,因为ID在页面中应该是唯一的。

Anyway, if you really want to be more specific, the correct way to retrieve a canvas with this ID is to remove your space there: $('canvas#whatever') 无论如何,如果你真的想要更具体,检索具有此ID的画布的正确方法是删除你的空间: $('canvas#whatever')

Try this, $('canvas#whatever') 试试这个, $('canvas#whatever')

This should work. 这应该工作。

if you want multiple elements with the same identifier use classes and then reference it $("canvas .yourclass"). 如果你想要多个具有相同标识符的元素使用类,然后引用它$(“canvas .yourclass”)。 I'm not sure if thats what's causing your issue but if its not a unique ID it's not right. 我不确定那是什么导致你的问题,但如果它不是一个唯一的ID,那就不对了。

Try class = whatever instead, seems to work better. 尝试class = what,似乎效果更好。 Canvases with the same Id behave strangely. 具有相同Id的画布表现奇怪。

 $('.whatever').css('background-color','green'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <canvas class="whatever" width="50px" height="50px"></canvas> <canvas class="whatever" width="50px" height="50px"></canvas> <canvas class="whatever" width="50px" height="50px"></canvas> 

The empty space you leave after the element type implies that the following selector concerns children of that element. 在元素类型之后留下的空白空间意味着以下选择器涉及该元素的子元素。 You need to keep the whole selector tight together, no spaces. 你需要保持整个选择器紧密,没有空格。

$('canvas#whatever')

Try this 尝试这个

$('canvas#whatever')

or 要么

$('canvas[id=whatever]')

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

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