问题
I am working on rails 3.2 and using coffeescript too.. I have a doubt in using jquery mobile inside my application I have a html like
<a href="#" data-item=12 data-status=true class="follow">
<span class="ui-btn-inner">
<span class="ui-btn-text">
Follow
</span>
</span>
</a>
In my coffeescript, i am trying to write function on click of this Follow, i am trying to send a ajax call.
when i wrote like
$("a.follow").unbind('click').bind 'click', (event, data) ->
event.stopPropagation()
clickedEl = $(event.target)
console.log(clickedEl)
Console.log prints span with class "ui-btn-text" at times and span with "ui-btn-inner" at times.
But in my coffeescript function , i need to actually take attributes from a tag. How to proceed with this
回答1:
You can use event.currentTarget instead of event.target
:
The current DOM element within the event bubbling phase.
Demo: http://jsfiddle.net/ambiguous/gdzUC/
Or event.delegateTarget:
The element where the currently-called jQuery event handler was attached.
Demo: http://jsfiddle.net/ambiguous/UhBWM/
You could also use closest:
clickedEl = $(this).closest('a')
Demo: http://jsfiddle.net/ambiguous/2LHp3/
The event.target value is:
The DOM element that initiated the event.
In other words, it is the thing that was actually clicked on. The currentTarget
and delegateTarget
will be the thing that the event is bound to. Using closest
is probably overkill for this, you'd usually use that to go up the DOM to an container that holds several items that you're interacting with.
回答2:
You can use jQuery to always get the link element, you then have a reference to work from if you need info from the contained spans.
...
clickedEl = $(event.target)
parentLink = clickedEl.parentsUntil $("a.follow")
console.log(parentLink)
来源:https://stackoverflow.com/questions/10613787/binding-click-event-in-jquery-coffeescript