单击在initilazion上运行但不起作用的Listener

时间:2017-04-26 15:24:33

标签: javascript jquery

我正在学习javaScript / jQuery,我想要做的就是使用一个循环在屏幕上放几张图片并设置一个每次增加的计数器,点击图片。 从其他stackoverflow问题中,我了解到,对于动态添加的DOM-Elements,我不能使用jQuery的.click(),而应该使用.on(' Click',' selector' '功能&#39)。但这并没有解决它。

对我来说,列表器中的代码有一段时间(即每只狗的计数器设置为1),然后点击一张图片就会产生:

jquery.min.js:3 Uncaught TypeError: ((n.event.special[g.origType] || (intermediate value)).handle || g.handler).apply is not a function
    at HTMLDivElement.dispatch (jquery.min.js:3)
    at HTMLDivElement.r.handle (jquery.min.js:3)

这是我的代码:

我特别感兴趣/参考这一部分:

// add a click counter to the click-per-dog-array
        // initialize array element
        clicksPerDog[i] = 0;
        idString = "#"+wugel;
        // create listener
        $('#dogsWrapper').on('click',idString,function(j,fidString){

            console.log("the j passed to the function is: "+j.toString());
            //increase click counter
            clicksPerDog[j]++;
            // update text
            $(fidString).text('This dog has been clicked: '+clicksPerDog[j].toString()+" times.");
        }(i,idString));

对于那些感兴趣的人,这里是整个shebang:

/*
*
* Click counter practice
*
*/

// HTML bits and variables to reuse for each dog
var HTMLDogContainer= "<div id='%dogname%' class='dogcontainer'></div>";

var HTMLDogName = "<h1 >%dogname%</h1>";
var HTMLDogImage = '<img src="resources/%dogname%.jpg" alt="%dogname%" class="dogpic">';
var HTMLCounterText ='<div class="counterText" id="%idtext%"> This dog has not been clicked yet. Counter is %numberClick%.</div>';
var HTMLDogButton ='<button type="button" class="btn btn-primary">%dogname%</button>';

var dogNames = ["Bonzo","Fox","Jimbo","Larry","Mike"];
console.log("dogNames length is this: "+dogNames.length.toString());
var clicksPerDog = [];

var tmpDogContainer, tmpDogName, tmpDogImage, tmpCounterText, tmpDogButton, tmpIdString;

// Let's loop over the dogs in our array and create the elements
for (var i = 0; i < dogNames.length; i++) {  // The number, when thinking 1-indexed, we're on is simply i+1
    // Create a div containing the whole shebang for each dogs
    tmpDogContainer = HTMLDogContainer.replace('%dogname%', dogNames[i]);
    tmpIdString = '#' + dogNames[i]; // Make it identifiable in this loop for jQuery ID Selector purposes
    console.log('tmpIdString: ' + tmpIdString);
    $('#dogsWrapper').append(tmpDogContainer); // append it to the DOM

    // create content for the dog and append it to its respective wrapper
    tmpDogName = HTMLDogName.replace('%dogname%', dogNames[i]); // header with dogname
    $(tmpIdString).append(tmpDogName);

    tmpDogImage = HTMLDogImage.replace('%dogname%', dogNames[i]); //image
    $(tmpIdString).append(tmpDogImage);

    tmpCounterText = HTMLCounterText.replace('%numberClick%', '0'); //counter
    var wugel = dogNames[i].toString() + "counter";
    tmpCounterText = tmpCounterText.replace('%idtext%', wugel); //counter
    $(tmpIdString).append(tmpCounterText);

    // create a button for the dog
    tmpDogButton = HTMLDogButton.replace('%dogname%', dogNames[i]);
    $('#dogSelector').append(tmpDogButton); // append it to the DOM

    // add a click counter to the click-per-dog-array
    // initialize array element
    clicksPerDog[i] = 0;
    idString = "#"+wugel;
    // create listener
    $('#dogsWrapper').on('click',idString,function(j,fidString){

        console.log("the j passed to the function is: "+j.toString());
        //increase click counter
        clicksPerDog[j]++;
        // update text
        $(fidString).text('This dog has been clicked: '+clicksPerDog[j].toString()+" times.");
    }(i,idString));

  }

对于这个HTML:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Doggo</title>
  <!-- Latest compiled and minified Bootstrap CSS -->
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
  <!-- My own CSS -->
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <div class="container">
    <div id="dogsWrapper">

    </div>
    <div class="dog-selection-area">
      <p>Select the dog you would like to click:</p>
      <div id="dogSelector" class="btn-group">
      </div>
    </div>
  </div>
  <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <!-- Latest compiled and minified Bootstrap JavaScript -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
  <script src="js/skript.js"></script>
</body>

</html>

1 个答案:

答案 0 :(得分:0)

看看这个示例实现。 单击“尚未点击此狗。”,增加点击次数。 将其作为进一步改变的方向。

很少有事情需要注意:

  1. 您没有将代码包装在$(document).ready。
  2. 由于您需要为每只狗提供一个计数器,您可能需要一个对象,其中狗名称将成为关键,而点击计数将作为值。
  3. 我已更正此示例的代码。
  4. $(document).ready(function () {
    
    
            // HTML bits and variables to reuse for each dog
            var HTMLDogContainer = "<div id='%dogname%' class='dogcontainer'></div>";
    
            var HTMLDogName = "<h1 >%dogname%</h1>";
            var HTMLDogImage = '<img src="resources/%dogname%.jpg" alt="%dogname%" class="dogpic">';
            var HTMLCounterText = '<div class="counterText" id="%idtext%"> This dog has not been clicked yet. Counter is %numberClick%.</div>';
            var HTMLDogButton = '<button type="button" class="btn btn-primary">%dogname%</button>';
    
            var dogNames = ["Bonzo", "Fox", "Jimbo", "Larry", "Mike"];
            //console.log("dogNames length is this: " + dogNames.length.toString());
            //var clicksPerDog = [];
    
            var tmpDogContainer, tmpDogName, tmpDogImage, tmpCounterText, tmpDogButton, tmpIdString;
    
            // Let's loop over the dogs in our array and create the elements
            for (var i = 0; i < dogNames.length; i++) {  // The number, when thinking 1-indexed, we're on is simply i+1
                // Create a div containing the whole shebang for each dogs
                tmpDogContainer = HTMLDogContainer.replace('%dogname%', dogNames[i]);
                tmpIdString = '#' + dogNames[i]; // Make it identifiable in this loop for jQuery ID Selector purposes
                //console.log('tmpIdString: ' + tmpIdString);
                $('#dogsWrapper').append(tmpDogContainer); // append it to the DOM
    
                // create content for the dog and append it to its respective wrapper
                tmpDogName = HTMLDogName.replace('%dogname%', dogNames[i]); // header with dogname
                $(tmpIdString).append(tmpDogName);
    
                tmpDogImage = HTMLDogImage.replace('%dogname%', dogNames[i]); //image
                $(tmpIdString).append(tmpDogImage);
    
                tmpCounterText = HTMLCounterText.replace('%numberClick%', '0'); //counter
                var wugel = dogNames[i].toString() + "counter";
                tmpCounterText = tmpCounterText.replace('%idtext%', wugel); //counter
                $(tmpIdString).append(tmpCounterText);
    
                // create a button for the dog
                tmpDogButton = HTMLDogButton.replace('%dogname%', dogNames[i]);
                $('#dogSelector').append(tmpDogButton); // append it to the DOM
    
                // add a click counter to the click-per-dog-array
                // initialize array element
                
                //idString = "#" + wugel;
                // create listener
            }
            clicksPerDog = {
                Bonzocounter: 0,
                Foxcounter: 0,
                Jimbocounter: 0,
                Larrycounter: 0,
                Mikecounter: 0
    
            };
            $('#dogsWrapper').on('click', function (e) {
    
                var id = e.target.id;
                if (id.indexOf('counter') >=0) {
                    clicksPerDog[id]++;
                    // update text
                    $('#' + id).text('This dog has been clicked: ' + clicksPerDog[id] + " times.");
                }
                
            });
            });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container">
        <div id="dogsWrapper">
            
        </div>
        <div class="dog-selection-area">
          <p>Select the dog you would like to click:</p>
          <div id="dogSelector" class="btn-group">
              Dog
          </div>
        </div>
      </div>