html div onclick event

前端 未结 9 1092
渐次进展
渐次进展 2021-02-05 13:23

I have one html div on my jsp page, on that i have put one anchor tag, please find code below for that,

9条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 14:13

    The problem was that clicking the anchor still triggered a click in your

    . That's called "event bubbling".

    In fact, there are multiple solutions:

    • Checking in the DIV click event handler whether the actual target element was the anchor
      → jsFiddle

      $('.expandable-panel-heading').click(function (evt) {
          if (evt.target.tagName != "A") {
              alert('123');
          }
      
          // Also possible if conditions:
          // - evt.target.id != "ancherComplaint"
          // - !$(evt.target).is("#ancherComplaint")
      });
      
      $("#ancherComplaint").click(function () {
          alert($(this).attr("id"));
      });
      
    • Stopping the event propagation from the anchor click listener
      → jsFiddle

      $("#ancherComplaint").click(function (evt) {
          evt.stopPropagation();
          alert($(this).attr("id"));
      });
      


    As you may have noticed, I have removed the following selector part from my examples:

    :not(#ancherComplaint)
    

    This was unnecessary because there is no element with the class .expandable-panel-heading which also have #ancherComplaint as its ID.

    I assume that you wanted to suppress the event for the anchor. That cannot work in that manner because both selectors (yours and mine) select the exact same DIV. The selector has no influence on the listener when it is called; it only sets the list of elements to which the listeners should be registered. Since this list is the same in both versions, there exists no difference.

提交回复
热议问题