开发者

How can I create functions in jQuery and call it on event and pass variable to it?

$(".addcart").click(function(){

   $("input[name='items']:checked").each(function() {
       //doing something
   });

});

I'm trying to create a common class onclick of which I'm doing something. Is there a way I can make "items" a variable, I mean Can I pass开发者_JAVA百科 checkbox name to this event.


Try this and see if it works out:

$("input[name='items']:checked").each(function() {
  alert(this.attr("name"));
});

I think I've used like this somewhere.

[EDIT] The thing with this is that jQuery passes the current item to the foreach as the context of the variable.


Use bind instead of click

$(".addcart").bind("click", {name: "items"}, function(event){
   $("input[name='" + event.data.name + "']:checked").each(function() {
       //doing something
   });
});

edit:

"How can I create functions in jQuery and call it on event and pass variable to it"

That will still be the same procedure. Use bind to attach an event handler, pass it an object with the needed stuff for your function. In your event handler call your function and pass it the object from event.data

$(".addcart").bind("click", {foo: "hello world"}, function(event) {
   DoSomethingOnClick(event.data);
});

function DoSomethingOnClick(obj) {
   obj = obj || {};
   if (obj.hasOwnProperty('foo'))
      alert(obj["foo"]);
   else
      alert("no foo here");
}


You know that all checked items will have a name of items, so that's not very interesting, but maybe you want to retrieve the value of each of the items:

$(".addcart").click(function(){

   $("input[name='items']:checked").each(function() {

         // To access an attribute of this item use the form $(this).attr(...)
       alert( this.value );

   });

});

The above uses this to access the element being iterated over. Take a look at the properties of a DOM element to see what properties of this you can access.

You can create a jQuery object out of this using the form $(this) then you can use .attr() to access the attributes of this. For example to get the class/es of this you can use either this.className or $(this).attr("class").

It is faster to directly access the DOM element's properties. But for some more complex manipulations it is good to know that $(this) is also available.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜