在jquery选择器中使用变量 [英] using variables within a jquery selector

查看:164
本文介绍了在jquery选择器中使用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用以下代码构建动态jquery选择器:

  var section_id ={segment_3} ; 
var num_children = $('#'+ section_id +'ul')children()。size();

其中segment_3是我从url字符串中成功检索的值,例如可能返回值section_one



但是当尝试创建变量num_children时,此引用不起作用。如何构建代码来构建动态引用?感谢任何帮助。

解决方案

假设var section_id ='section_1'这个:



(pre> $('#'+ section_id +'ul')。

会给你

  $('#section_1 ul')。children()。size(); 

是的,这也是有效的。它将给你#start1元素中的所有ul元素(无论它们有多深)。可能你会得到数组的元素,并调用.children()就可以了。它应该都可以工作。


I'm trying to build a dynamic jquery selector with the following code:

var section_id = "{segment_3}";
var num_children = $('#'+ section_id + ' ul').children().size();

where segment_3 is a value I successfully retrieve from the url string, which, for example, might return the value of "section_one"

But when trying to create the variable num_children, this reference doesn't work. How do I construct the code to build a dynamic reference? Thanks for any help.

解决方案

Assuming var section_id = 'section_1' this:

$('#'+ section_id + ' ul').children().size();

will give you

$('#section_1 ul').children().size();

and yes, this is valid as well. It will give you all ul elements within #section_1 element (no matter how deep they would be). Probably you'll get array of elements and calling .children() on it is also fine. It should all work.

这篇关于在jquery选择器中使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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