2015-04-02 94 views
0
<div class="hello" rel="1"></div> 
<div class="hello" rel="2"></div> 
<div class="hello" rel="3"></div> 

num = 3; 

为什么在选择器下面对我不起作用?我想根据元素的自定义属性选择hello类。选择元素基于其rel属性,变量为

var a = $('.hello[rel='+num+']'); 
+0

尝试使用双引号,像这样的'变种a = $('。hello [rel =''+ num +'“]');'。 – BabyDuck 2015-04-02 08:27:38

+0

控制台中显示任何错误?你有包括jQuery吗? 和你的num = 3放在

-1
var a = $('.hello[rel="'+num+'"]'); 

这将帮助你

+1

难道你不认为这样做实际上会分配属性值而不是获取? – 2015-04-02 08:29:42

+0

ops yes是我的worng。让我来核实一下,看看编辑后的答案 – Iceburg 2015-04-02 08:38:20

0

试试这个:

console.log($('.hello[rel=1]')); 

在所有的代码应该是这样的:

var num = 3; 
 
var a = $('.hello[rel='+num+']'); 
 
alert($(a).text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="hello" rel="1">1</div> 
 
<div class="hello" rel="2">2</div> 
 
<div class="hello" rel="3">3</div>