Jquery push function [closed]

懵懂的女人 提交于 2019-12-24 00:33:56

问题


I'm working on samsung SDK and modifying a javascript app for smart tv. I stumbled upon this piece of code and I don't understand what if($('.menuButton').push()){... does. The native push function was not overwrited but this still works. I thought push will append an element to an array, but this doesn't seem to be the case

if(direction==tvKey.KEY_ENTER){
        if($('.menuButton').push()){
            $('.simple_menu').slideDown('easy');
     ........

回答1:


Calling .push(x) on a JQuery selector acts the same as calling .push(x) on a normal array in Javascript.

From W3Schools and the Mozilla Developer Network:

The push() method adds new items to the end of an array, and returns the new length.

and

Returns: The new length property of the object upon which the method was called.

If no arguments are passed to .push(), then the array is left as-is, and the length is still returned. So what is happening here is the array length is being returned and used to evaluate the if statement.

Example: The following will return the number of p tags:

$("p").push();

But Beware: The .push method for JQuery objects is marked for internal use only and thus should not be depended on.




回答2:


This method should not be relied upon. Don't use it.

push() is defined on the jQuery object (which is an array-like object), and it maps to the native Array.prototype.push() method, but it is meant for internal use only, not documented and you cannot be sure it will work the same way in future versions.

In this code, it seems to be used to get the number of elements in the jQuery object (which is what the native .push() does, it returns the value of the length property).

But there is a documented way to do that:

$('.menuButton').length

The code relies on the fact that if the length is zero, it will evaluate to false in Javascript when converted to a Boolean, so the code in the if block will only run if the jQuery object is not empty.




回答3:


I'm not sure what $().push does or if it even exists (not to be confused with the native JavaScript array.push() method), but you are probably looking for $().add:

Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method.

Also note that a jQuery object can never be false, your if statement should probably be:

if($('.menuButton').add(something).length > 0) {

Edit: it looks like you are using an internal-only, undocumented, and unsupported method of jQuery. If you want to get the length of the current jQuery object (which is what $().push() appears to do), just use length:

if($('.menuButton').length > 0) {


来源:https://stackoverflow.com/questions/14524024/jquery-push-function

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