jQuery $(#id)和$([id =])有什么区别 [英] Jquery what is the difference between $(#id) and $([id=])

查看:286
本文介绍了jQuery $(#id)和$([id =])有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在程序中遇到这个问题时,我有点困惑.所以我想知道是否有人知道这可能是什么交易.我毕竟对Jquery还是很陌生.

I was a bit confused when I encountered this in my programm. So I was wondering if anyone knew what could be the deal here. I am fairly new to Jquery after all.

为什么这样做:

$('[id="' + nameOftheID + '"]').append("Append some text");

为我工作.

$("#" + nameOftheID).append("Append some text");

对我不起作用. 在这种情况下,"nameOftheID"是一个变量,它与 span 的ID完全相同(我尝试在其中附加一些文本)(我在调试中进行了测试并确认了这一点).为什么基于ID进行选择的普通#选择器没有为我添加文本.但是另一种方法呢?

does not work for me. In this case the 'nameOftheID' is a var that is exactly the same as the ID of the span I am trying to append some text to (I tested and confirmed this in debugging). Why is it that the normal # selector for selection based on ID's does not append the text for me. but the other method does?

我的代码最后可用.我只想知道为什么A有效而B无效?

My code works in the end. I just want to know why A works and B doesnt.

我的ID的名称是"Ruleset [0].条件[0]"

The name of my ID is "Ruleset[0].Conditions[0]"

推荐答案

您必须使用\\来转义字符

You have to use \\ for escape characters

#Ruleset\\[0\\]\.Conditions\\[0\\]

以下是两个选择器的区别:

Below is the differnce for two selectors :

$("#" + nameOftheID).append("Append som text");

以上代码是按ID选择元素的,此处的语法是使用#.

Above code is to select element by ID and here syntax is to use #.

还有

$('[id="' + nameOftheID + '"]').append("Append some text");

这位于属性选择器下,您可以在其中限制对特定标记的选择,如下所示:

This comes under attribute selector, where you can restrict the selection for specific tag like below

$('input[id="inputId"]').append("Append some text");// here it will check the id attribute of input tag only

此外,属性选择器还可用于查找以某些文本开头的值的元素,例如以id开头为'nameOf'的find输入

Also, attribute selectors can be use to find elements with value start with some text like find input with id start with 'nameOf'

$('input[id^="nameOf"]').append("Append some text");

因此,属性选择器可用于获取具有更多过滤功能的元素或进行更精确的选择.请在此处找到更多有关选择器的信息.

Hence attribute selectors can be used for get elements with more filtering or for more precise selections. Please find more on selectors here.

这篇关于jQuery $(#id)和$([id =])有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆