Reputation: 27
I have a very confusing problem. I want to do some action within an HTML site, when a link is clicked. I implemented the following code with a click event, which should handle this behaviour:
$(document).ready(function() {
console.log("Ready!");
$( "a" ).click(function() {
console.log("Alert!");
alert("Test");
});
});
I implmented it in the head and at the end of the body but nothing happens. I don't get the console.log or alert. When I change the click to mouseover everything ist fine. Do you have any suggestions?
Regards, Jens
Upvotes: 0
Views: 135
Reputation: 1437
please see this : jsfiddle
$(document).ready(function() {
console.log("Bereit!");
$( "a" ).click(function() {
console.log("Alert!");
alert("BBB wurden mit dem CCC synchronisiert");
});
});
its works.
Are you sure you've added the correct version jQuery?
Upvotes: 0
Reputation: 11186
Make sure to include Jquery in your head:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
$(document).ready(function() {
console.log("Ready!");
$('a[href$="google"]').on("click",function() {
console.log("Alert!");
alert("Test");
});
});
</script>
</head>
<body>
<a href="google">google</a>
</body>
</html>
Otherwise you can get DOM elements by using: getElementsById and add id in your link
Upvotes: 0
Reputation: 11
The first thing that you need to do is check you jquery library to make sure that you have included it or not?
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
If it still doesn't work you should check your anchor attribute and change it like bellow
<a href="#">alert</a> or <a>alert</a>
So this code will work
$(document).ready(function() {
console.log("Ready!");
$( "a" ).click(function() {
console.log("Alert!");
alert("Test");
});
});
Upvotes: 0
Reputation: 1531
Is the a
present when the page is loaded? If not, you need to modify your event binding a little.
Also, you can try to prevent the default behavior.
$(document).ready(function() {
console.log("Ready!");
$(document).click("a", function(e) {
e.preventDefault();
console.log("Alert!");
alert("Test");
});
});
Upvotes: 0
Reputation: 1041
try using
$(document).ready(function() {
console.log("Ready!");
$( "a" ).on("click",function() {
console.log("Alert!");
alert("Test");
});
});
because some versions of Jquery don't support the click function alone
Upvotes: 1