简体   繁体   中英

JQuery - .click triggering when clicked anywhere should: upon clicking on a link

https://dl.dropboxusercontent.com/u/63617776/Capture.PNG

So as on the image, when you click on the map, a div is changed. Now when I click on a link in the div, I want the google maps div to change to another map.

But, the code I wrote either doesn't trigger at all or it triggers when I click anywhere on the page.

$('#nowydwor').ready(function(){
$(this).click(function(){
         alert('foo');
    });
});

Ofcourse the link looks like this: {a id="nowydwor"} text {/a} (for some reason i couldn't enter < so I replaced it with {)

This triggers when user clicks anywhere on the page, for some reason. Also this is only a testcode for now, it is meant to display the alert. :) Any ideas?

EDIT: The link is contained in .html(), in a switch() statement.

case '#mazowieckie':
   $('#info').html("CONTENT </h5><hr><strong><a id='nowydwor'>Skład Nowy Dwór Mazowiecki</a></strong> CONTENT");      

break;

Calling ready only makes sense if you call it on the document / window to get notified as soon as the DOM is ready.

Try to bind the click handler on your DOM element directly:

$('#nowydwor').on('click', function(){
  alert('foo');
});

I think what you were trying to do, is assign the click handler after the content of #info has changed. Unfortunately .ready() is only an event handler for the document ready event. It only fires once. Also changing the html of '#info' isn't triggering any events (IMHO).

You can work around this, using the .on -method on a parent element. Consider this html structure:

<div id="info">
  <!-- This content is dynamically loaded -->
  <a id="nowydwor">Click this to change map</a>
  <!-- End of dynamic content -->
</div>

This makes it possible to call:

$('#info').on('click', '#nowydwor', function(){ /* Change map here... */ })

This assigns the event handler to #info , which is only called if the clicked element matches '#nowydwor' . Since '#info' is never removed, only the content changes, you don't have to apply it again.

The only point is, you have to determine what the id of the map/place is, because the event handler will be the same for all links.

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