简体   繁体   中英

Applying styles to multiple selectors

Why doesnt the following apply the css rules to both elements?

var prevElem = $('<a href="#" class="'+ settings.prev +'" />').text('Prev');
var nextElem = $('<a href="#" class="'+ settings.next +'" />').text('Next');
container.append(prevElem, nextElem);
$(prevElem, nextElem).css('top', container.height()/2);

Its only applied to prevElem.

Please note that the dynamic elements have been added to the DOM (with their classes) so they are there.

To do what you need, you must call add() method.

var prevElem = $('<a href="#" class="'+ settings.prev +'" />').text('Prev');
var nextElem = $('<a href="#" class="'+ settings.next +'" />').text('Next');

prevElem.add(nextElem).appendTo(container).css('top', container.height()/2);

Reason you can't join arrays by providing them as parameters to jQuery , is that there is simply no such API. And there shouldn't be because it would make it impossible to implement jQuery( selector [, context] ) which searches for elements within context. Check out $.add() for what you attempted to do.

Your code should be:

prevElem.add(nextElement).css('top', container.height()/2);

If you have a look at the documentation of jQuery you will see that you cannot create a jQuery object with two elements the way you tried. Read the documentation, there is no need to guess how it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM