views:

68

answers:

4

my code and my problem is:

<script type="text/javascript">
$(document).ready(function() {
  // this variable is used to set the dynamic elements
  tagFlag = '';

  $("#a1").click(function(event) {
      event.preventDefault();
      tagFlag = 'me';  // setting the element which I want to trigger later
  });

  $('#'+tagFlag).click(function(e) {
      // do sthing here
  });
});

</script>
</head>

<body>
<a href="">make the element</a>
<p id="me">some words here</p>
</body>
</html>

but.when I set the tagFlag,and click the "p" nothing is happen.BTW.there is error when tagFlag had been set nothing.So.How can I get what I want?

Thank you very much!!

A: 

Maybe you should look at the jQuery live() method that will assign event to all existing and future elements.

http://api.jquery.com/live/

Tomasz Kowalczyk
That won't help.
SLaks
I tried it before.Live() method change nothing....And if I set the tagFlag = ''; I got this error:uncaught exception: Syntax error, unrecognized expression: #
qinHaiXiang
A: 

There is no element wit the ID "a1". If you want the first anchor element use

$.("a:eq(0)")

instead.

If that's not it, report back please.

FK82
A: 

use a jquery object and add the clicked elements to it:

$(document).ready(function() {
  $tagFlag = $("");

  $("#a1").click(function(event) {
    event.preventDefault();
    $tagFlag.add($(this));
  });

  $tagFlag.click(function(e) {
    // do sthing here
  });

});
elektronikLexikon
This won't work, the `click` event will be bound to no elements...remember you're binding to the element references in the jQuery object when `.click()` is run, adding elements later won't add an event handler to them.
Nick Craver
ok, that's right. Sorry...
elektronikLexikon
A: 

You can attach a .click() handler to document and check if the target of the click was the element you cared about, similar to how .live() behaves internally, like this:

$(function() {
  var tagFlag = '';
  $("#a1").click(function(event) {
      event.preventDefault();
      tagFlag = 'me';
  });
  $(document).click(function(e) { 
    if(tagFlag &&                  //is it even set?
       (e.target.id == tagFlag || $(e.target).closest('#'+tagFlag).length)) {
          //do work here
    }
  });
});

You can give it a try here, the only change to your markup is the addition of a child element (to show click bubbling/handling working) and giving the anchor that a1 ID I think you intended for it to have in the question.

Alternatively if you know the set of elements that may be clicked, give them a class and bind a handler to them, checking the ID like I have above...or unbind the class and rebind to the specific ID each time, there's a few ways to go about this :)

Nick Craver