简体   繁体   中英

Unable to implement onclick event on HTML element

I have an array of 10 elements. At first I want to shuffle the array elements and display them (my current code does this). Then I want to show an alert message if any of the displayed array elements are clicked. This is the thing I am having problem with. If, I am doing onclick , it's showing me only 1 array element instead of all the 10 array elements and also showing the following error in console Uncaught TypeError: Cannot set property 'onclick' of undefined . My code is (I am using only javascript ):

 <script>
    function shuffleArray(array) {
            for (var i = array.length - 1; i > 0; i--) {
                var j = Math.floor(Math.random() * (i + 1));
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
                }
            return array;
        }

    var myArray = ['1','2','3','4','5','6','7','8','9','10'];

    newArray = shuffleArray(myArray);

    for (i=0;i<newArray.length;i++) {
        var p = document.write(newArray[i] + "<br >");
                    p.onclick = showAlert; // this is showing me only 1 array element and also showing error in concole
    }

             function showAlert() {
                      alert("onclick Event detected!")
             }
 </script>

You need to create an actual element, rather than trying to bind events to strings:

for (i=0;i<newArray.length;i++) {
    var p = document.createElement('p');
    p.innerHTML = newArray[i];
    p.onclick = showAlert; 
    document.body.appendChild(p);
}

http://jsfiddle.net/92fRb/1/

for (i=0;i<newArray.length;i++){
    var p = document.write("<span class='no'>"+newArray[i] + "</span><br />");
}

function showAlert(){
    alert("onclick Event detected!")
}

for(i=0;i<document.getElementsByClassName("no").length;i++){
    document.getElementsByClassName("no")[i].onclick=showAlert;
}

Cannot set property 'onclick' of undefined

Here's your problem... p is undefined.
Why?
Because document.write does not return a DOM element. Actually it does not return anything at all (or, returns undefined ).

You want to:

  1. Use document.createElement() to create an element.
  2. Use p.innerHTML to set the content (inner HTML) of your new element.
  3. Append your new element to the document.

Your code can be revised as suggested in @Johan's answer .

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