I want to perform some action when a link is clicked, I am using the following code to achieve this however it rarely works. If I click the link it usually refreshes the page, and 1/10 times it'll actually pop up "Hi". What is wrong?
$(document).ready(function()
{
$('#slconfiglink').click(function()
{
alert("hi");
return false;
});
});
HTML:
<ul>
<li><a href="#" id="slconfiglink">Config 1</a></li>
</ul>
Note that the ID's are not replicated elsewhere in the HTML
Make sure to give your <a>
a valid href
, like this:
<a href="#" id="slconfiglink">Config 1</a>
Your anchor needs to have an href
or a name
to be valid, otherwise you'll get some funny behavior that'll vary by the browser used.
Also, unless you need the anchor for hover CSS, etc...you have the option to put the click handler right on the <li>
, like this:
<ul>
<li id="slconfiglink">Config 1</li>
</ul>
A few other things to check, make sure that ID is unique, if it's not use a class, like class="slconfiglink"
and your selector would be ".slconfiglink"
instead of "#slconfiglink"
.
If your elements are being added on the fly, change from
$('#slconfiglink').click(function() {
To use .live()
like this (or with the class selector, if the multiple comment applies):
$('#slconfiglink').live('click', function() {
Is the element being created dynamically? If you are adding it using Javascript, you'll need to reattach your event handler after it's been added to the DOM.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With