Selecting a variable's nested elements - jQuery

雨燕双飞 提交于 2019-12-20 03:38:11

问题


I wish to pass a variable to a function and have the function select elements within that variable. I'm unfamiliar with the syntax of this case however, could any one advise?

For example, when a button is clicked within a container I wish for that container to be stored in a variable, okay I have that part. But then I wish to select a certain element within that container like

$(container "div#element");

How can you combine the two, noting that these elements could be deeply nested?


回答1:


jQuery gets a second parameter, which determines the scope of the selection. For example $('#first-name', '#registration-form') only matches elements with the first-name id inside registration-form.

I guess you can use this feature. I think $("div#element", container); would work.

See this fiddle.




回答2:


For chainability you can also use:

$(container).find('#element');



回答3:


Use find if you are searching the Dom.

function doSomething(container) {
  var $element = $(container).find('#element');

  // .. Now do something

}

Use filter if you are wanting to search only the elements contained by container.

function doSomething(container) {
  var $element = $(container).filter('#element');

  // .. Now do something

}


来源:https://stackoverflow.com/questions/7455374/selecting-a-variables-nested-elements-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!