jQuery combine multiple elements

北城以北 提交于 2019-12-20 03:29:09

问题


I was experimenting with jQuery and came across a question. Can I use an actual selector with existing element as a combined selector for jQuery?

So, suppose I've created a DIV element on-the-fly:

var $div = $('<div>')
               .css('position', 'absolute')
               .hide();    // Just to be short

$('body').append($div);

And I want to show it when user hovers over P elements / paragraphs (at the cursor position):

$('p').hover(function(e) {

    // Change the position of $div with regards of cursor position

    $div.show();
}, function(e) {
    $div.hide();
});

BUT also I want to apply this hover handlers to $div itself. So instead of duplicating my code, I want to do something like this:

$('p', $div).hover(...)

which will select $div element along with all P elements.

I know I can write functions separately and pass the names as arguments to hover function.

Is there any solution to this kind of situation in jQuery? or is there a more accurate solution?


回答1:


You could use the jQuery add method:

$('p').add($div).hover(function(e) { ...



回答2:


If you have multiple elements to combine you don't wan to do

$('p').add($div1).add($div2).add($div3).add($div4).add($div5).add($div6) ...

Instead you want to convert a JavaScript array into a jQuery object

$( $.map([x,y,z], a => [...$.makeArray(a)]) )

Source: Merging jQuery objects



来源:https://stackoverflow.com/questions/23994622/jquery-combine-multiple-elements

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