简体   繁体   中英

javascript .push() doesn't seem to work

I am trying to use .push to put items into a javascript array. I have created a simplified piece of code. When I click the button with id clickButton, I am expecting to get a series of alerts with numbers, but I get nothing.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Sempedia | Making computers think about data the way we do</title>
 <link href="css/styles.css" rel="stylesheet" type="text/css" />
 <script type="text/javascript" src="js/jquery.js"></script>
 <script>
    $(document).ready( function() {
    var myArray = new Array(); //declare the array

    for(var i=0;i<=10;i++){   // create a loop
        myArray.push(i);  // add an item to array
    }

    $("#clickButton").live('click',function() {  //register the button being clicked
    for(var j=0;j<=10;j++){    //for loop
        alert(myArray[j]);   //alert one item in the array
        }
    });

});
 </script>
 </head>
 <body>
 <input type="button" value="click me" id="clickButton" />
 </body>
 </html>

Works for me. You probably have an error elsewhere on the page.

Here is url to help you reference the jquery library. http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js

Use valid html, see http://validator.w3.org/

Do not include useless comments such as "//for loop" ; if somebody does not recognize a for loop, that comment is certainly not going to help much. None of those comments are going to be of any help anybody.

It is important to simplify and remove everything that is unrelated to the problem, such as the link tag. This will help make it clearer as to what the code is doing.

While you're at it, drop jQuery and learn to understand what you are doing.

The use of jQuery has increased drastically over the past two years. It is now employed for all sorts of things; things that are not only trivial to accomplish without jQuery, but are actually easier to accomplish without jQuery. This is often accompanied by complaints that the code does not do what is wanted of it, when all that was required to know why was a very basic understanding of the pertinent technologies.

Now to your problem. You want it to work and it doesn't[1].

The problem you need to solve is to get the event handler to fire. If a delegation strategy is desired, such as that you've attempted with jQuery live , then that can be accomplished by adding a click callback on document that inspects the target and handles it, accordingly.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>Me | Trying to make you think</title>
 <script type="text/javascript">
(function(){
    var myArray = [1,2,3];

    document.onclick = function(ev) {
        var target = getTarget(ev);
        if (target && target.id == "clickButton") {
            handleClickButtonClicked();
        }
    };

    function handleClickButtonClicked() {
        alert(myArray);
    }

    function getTarget(ev) {
        ev = ev || window.event;
        return ev ? ev.target || ev.srcElement : null;
    }
})();
 </script>
 </head>
 <body>
 <p><input type="button" value="click me" id="clickButton"></p>
 </body>
</html>

However, given your level of ability, I would advise going even simpler and just adding an onclick event handler to the button directly.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
        "http://www.w3.org/TR/html4/strict.dtd">
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 <title>Me | Trying to make you think</title>
 <script type="text/javascript">
    var myArray = [1,2,3];
 </script>
 </head>
 <body>
 <p><input type="button" value="click me" onclick="alert(myArray)" id="clickButton"></p>
 </body>
</html>

[1] http://jibbering.com/faq/notes/posting/#ps1DontWork

I have no idea what i did but it sudently started working.same code because i have returned back at start after playing around with diferent posible solutions. Coding magic.

I have tried doing this before it started runing, but then i removed [] .

    const recipeData = [{
      id: (Math.random() * 100).toString(),
      title: enteredTitle,
      image: enteredImg,
      ingredients: enteredingredients,
      description: enteredDescription,
    }];

Declare myArray outside the scope of the document.ready function. For example:

<script> 
  var myArray = new Array(); //declare the array
  $(document).ready( function() { 

    for(var i=0;i<=10;i++){   // create a loop 
        myArray.push(i);  // add an item to array 
    } 

    $("#clickButton").live('click',function() {  //register the button being clicked 
    for(var j=0;j<=10;j++){    //for loop 
        alert(myArray[j]);   //alert one item in the array 
        } 
    }); 

}); 
 </script>

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