-1

I have used the event handler to change the message but after clicking the link the message is not changing.

<a href="javascript:void(0);">Test 1</a>
<a href="javascript:void(0);">Test 2</a>

Here is the Javascript file:

$("a").bind("click", { message : msg }, function(event) {
    msg = "Changed msg";
    alert(event.data.message);
  });
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tazbirul Haque
  • 233
  • 1
  • 3
  • 15
  • 1
    ... because that's not how this works... you can't just arbitrarily set a variable's value and expect it to change a property of an object. well, i guess you could expect that, but you'd be mistaken. – Kevin B Nov 16 '17 at 16:46
  • http://api.jquery.com/bind/ read the section about eventData, it is not what you think it is – Huangism Nov 16 '17 at 16:46
  • oh. i thought it works like normal variable. we can not change it by assigning any arbitrary value. – Tazbirul Haque Nov 16 '17 at 16:48

1 Answers1

1

If you want to change the text of the anchor tag, you can do so like this:

$("a").bind("click", function(event) {
  $(event.target).text('Changed msg');
});

This can be shorted as this inside of the event handler will refer to event.target or what you've bound the function to (the anchor tag). So you can write the above like so:

$("a").bind("click", function() {
  $(this).text('Changed msg');
});

You can't simply set values to mutate the document object model (DOM). You need to use methods like text and html to tell jQuery what you want to do. You can do so with vanilla JavaScript.

As mentioned in the comments, eventData is an object you can include to pass long to the event handler. But it can't mutate or change things.

Cymen
  • 14,079
  • 4
  • 52
  • 72
  • or just use `$(this)` – Huangism Nov 16 '17 at 16:49
  • @Cymen what is the problem with my code? why can't i change the value by assigning like this? can you please tell me? – Tazbirul Haque Nov 16 '17 at 16:49
  • @TazbirulHaque Because you're randomly adding parameters to the bind function – kevinSpaceyIsKeyserSöze Nov 16 '17 at 16:50
  • 1
    @Huangism Yes but I figured better to keep it more obvious for now. But I updated to include it. – Cymen Nov 16 '17 at 16:50
  • 2
    @TazbirulHaque you need to read what eventData actually does http://api.jquery.com/bind/ if you just want to change the content of the anchor on click then this answer gives you what you want. Your original code use of eventData is not the right way, the purpose of eventData is not for what you want to use it for, again, read the section about it and understand it – Huangism Nov 16 '17 at 16:52
  • Thanks a lot for your suggestion – Tazbirul Haque Nov 16 '17 at 17:08