如何使用jQuery在list元素中单击图像?

时间:2017-03-10 21:40:38

标签: javascript jquery html

我正在尝试使用函数创建一个待办事项列表,以便让人们为重要项目加注星标。

这是我的index.html

<!DOCTYPE html>

<html>
  <head>
    <title>JavaScript &amp; jQuery - Chapter 7: Introducing jQuery - Example</title>
    <link rel="stylesheet" href="css/styles.css" />
  </head>
  <body>
    <div id="page">
      <h2>To Do List</em><span id="counter"></span></h2>
      <form id="newItemForm">
        <input type="text" id="itemDescription" placeholder="Add description" />
        <input type="submit" id="add" value="add" />
      </form>
      <ul id="list">
      </ul>
    </div>
    <script src="js/jquery-1.11.0.js"></script>
    <script src="js/example.js"></script>
  </body>
</html>

这是我的example.js,其中包含所有JavaScript功能

$(function() {

  // SETUP
  var $list, $newItemForm, $newItemButton;
  var item = '';                                 // item is an empty string
  $list = $('ul');                               // Cache the unordered list
  $newItemForm = $('#newItemForm');              // Cache form to add new items
  $newItemButton = $('#newItemButton');          // Cache button to show form

  $('li').hide().each(function(index) {          // Hide list items
    $(this).delay(450 * index).fadeIn(1600);     // Then fade them in
  });

  // ITEM COUNTER
  function updateCount() {                       // Create function to update counter
    var items = $('li[class!=complete]').length; // Number of items in list
    $('#counter').text(items);                   // Added into counter circle
  }
  updateCount();                                 // Call the function

  // ADDING A NEW LIST ITEM
  $newItemForm.on('submit', function(e) {       // When a new item is submitted
    e.preventDefault();                         // Prevent form being submitted
    var text = $('input:text').val();           // Get value of text input
    if(text != ""){
        $list.append('<li>' + text + '<div class="starItemButton"><img src="images/empty-star.png" alt="empty star"/></li>');      // Add item to end of the list
        $('input:text').val('');                    // Empty the text input
        updateCount();                              // Update the count
    }
  });

  // CLICK HANDLING - USES DELEGATION ON <ul> ELEMENT
  $list.on('click', 'li', function(e) {
    var $this = $(this);               // Cache the element in a jQuery object
    var complete = $this.hasClass('complete');  // Is item complete
    if(e.target.class == "starItemButton" || $(e.target).parents(".starItemButton").size){
      item = $this.text();             // Get the text from the list item
      $this.remove();                  // Remove the list item
      $list                            // Add back to end of list as complete
        .prepend('<li class=\"starred\">' + item + '<div class="starItemButton"><img src="images/full-star.png" alt="full star"/></li>')
        .hide().fadeIn(300);
    }
    else{
        if (complete === true) {           // Check if item is complete
          $this.animate({                  // If so, animate opacity + padding
            opacity: 0.0,
            paddingLeft: '+=180'
          }, 500, 'swing', function() {    // Use callback when animation completes
            $this.remove();                // Then completely remove this item
          });
        } else {                           // Otherwise indicate it is complete
          item = $this.text();             // Get the text from the list item
          $this.remove();                  // Remove the list item
          $list                            // Add back to end of list as complete
            .append('<li class=\"complete\">' + item + '</li>')
            .hide().fadeIn(300);           // Hide it so it can be faded in
          updateCount();                   // Update the counter
        } 
    }   // End of else option
  });                                  // End of event handler
});      

                       // End of event handler

正如您在我的$list.on('click'...方法中所看到的,我使用if(e.target.class == "starItemButton" || $(e.target).parents(".starItemButton").size){来测试点击是否发生在starItemButton div

但是,即使我在div外部单击,这个if语句似乎也会通过,我怎样才能获得一个只有当用户点击divstarItemButton时才能运行的函数?

非常感谢任何帮助,

谢谢

1 个答案:

答案 0 :(得分:1)

您可以将处理程序直接附加到图像,而不是整个列表项。然后,您不需要对目标执行检查,并且该事件仅在该元素上触发。

$list.on('click', 'li div.starItemButton', function(e) {
    // handler
});