html div onclick event

前端 未结 9 1113
渐次进展
渐次进展 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 <div>. 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.

    0 讨论(0)
  • 2021-02-05 14:13

    put your jquery function inside ready function for call click event:

    $(document).ready(function() {
    
      $("#ancherComplaint").click(function () {
         alert($(this).attr("id"));
      });
    
    });
    
    0 讨论(0)
  • 2021-02-05 14:14

    when click on div alert key

       $(document).delegate(".searchbtn", "click", function() {
            var key=$.trim($('#txtkey').val());
            alert(key);
            });
    
    0 讨论(0)
提交回复
热议问题