Reputation: 9063
I want to call a Jquery function with a hyperlink.
As I have it at the moment it is like this.
<a name='lnkViews'>" + title+ "</a>
$("a[name='lnkViews']").on("click", function (e) {
alert("Calling function");
});
As it is here it is not working. How can I call the function with the Hyperlink?
Upvotes: 3
Views: 31214
Reputation: 74410
Use delegation version of .on()
for dynamic created element:
$(document).on("click","a[name='lnkViews']", function (e) {
alert("Calling function");
});
Upvotes: 14
Reputation: 22580
Either Prevent Default Behavior or use the javascript:void(0)
trick.
$(function() { // simply document onload call, just pointing out where to put code, if you didn't already know
$(document).on('click', 'a[name=lnkViews]', function(e) {
e.preventDefault();
});
})
| OR |
<a name="lnkViews" href="javascript:void(0);">" + title+ "</a>
then, in your JS
$(function() {
$(document).on('click', 'a[name=lnkViews]', function(e) {
/* do work */
});
})
I noticed in your comments you said the link is created dynamically
, then my solution will work for you based on the fact I'm using the delegate
version of .on
. What this means, is the event is assigned to anything added to the document that matches the selector. thus the reason for the assignment the way it is:
$(document).on('click', 'a[name=lnkViews]', function(e) {
Upvotes: 3
Reputation: 1888
Which version of jquery do you use?
Put it into:
$(function()
{
js code
});
You've probably omitted it, but maybe it's not the thing because it looks you're adding link dynamically.
If so, try:
var link = "<a href='#' onclick='alert(\'Calling function\');'>" + title + "</a>";
Upvotes: 1
Reputation: 159
You can considere the following example : jquery sample
example
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<a id="aLink">First Paragraph</a>
<script>
$("#aLink").click(function () {
alert("Calling function");
});
</script>
</body>
</html>
Upvotes: 1
Reputation: 28588
It is working fine. Your code should contains });
for closing jquery function:
$("a[name=lnkViews]").on("click", function () {
alert("Calling function");
});
Upvotes: 1
Reputation: 841
You have to make sure that your a link is in the DOM when your on('click')
code is executed.
The jQuery function on()
will attach an event handler to all jQuery object contained in $("a[name='lnkViews']")
but if there is no element matching "a[name='lnkViews']"
in your DOM when $("a[name='lnkViews']").on()
is executed no handler will be attached.
To fix this you could do :
var $a = $('<a name="lnkViews">' + title+ '</a>');
$a.on("click", function (e) { });
//adding $a in your DOM with element.append($a); for exemple
You could also wait that your page is loaded before executing $("a[name='lnkViews']").on()
by doing this :
$(function() {
$("a[name='lnkViews']").on("click", function (e) { });
});
Regards
Upvotes: 1