jQuery Dollar Sign Confusion
I'm a bit confused regarding the dollar sign in jQuery, and was hoping someone could help me out.
I have the following function declaration:
$(function() {
$( "#create-discussion" ).button().click(function() {
alert("Clicked");
});
$( "#listitems tr" ).click(function(event) {
alert("clicked");
});
});
For some reason, the first function declaration for the "create-discussion" button works perfectly; when clicked, a popup appears. However, the second one does not work, and no popup is generated when I click on the table rows.
Is this some nuance in regards to button onClicks versus table row onClicks? Am I missing something stupidly obvious?
Also, I think it would help开发者_JS百科 a bunch if someone explained what $(function() {})
actually does, as I'm treating it like $(document).ready()
, and I'm not sure if I can do that.
A dollar sign ($
) is actually an alias for jQuery
function. And according to the documentation, if you pass a callback as an argument to this function, it will be executed when the DOM is ready.
When it comes to the second part of your question (about why the second part of the code is not working): just check the selectors. For me it is working perfectly (see jsfiddle - it is without .button()
method, because I am not loading jQuery UI), so this may be caused by incorrect selectors.
What you are doing should work so long as your selector text "#listitems tr" has something valid to select.
You can test by doing ... if the result is 0 that means jQuery did not find any valid items
alert($("#listitems tr").length);
When you make the call
$("a").click(function(evt) { alert("hello world!"); });
You are binding a click event to all <a> tags on your page. You could very well do the same with ...
$("a").click(myFunc);
function myFunc(evt) { alert("hello world!"); }
A click function can be attached to any html element. It does not have to be a button, it could be , , and etc. The element does not even have to be visible though you will only be able to fire the click if you call the actual event by doing ...
$("a").click();
The $("...") is just short hand for typing jQuery("...")
Hopefully this answers your questions.
精彩评论