开发者

What is a good way to transfer function arguments when using selectors?

I am trying to isolate my HTML from my js by replacing the following

<div id = "foo" onclick="bar(variable)"></div>

with

<div id = "foo"></div>
$(document).ready(function()    {
    $("#foo").click(function(event) {
        bar(???);
    });
});

Now, what would be a good way to transfer the parameter for bar().

开发者_高级运维

Should I merge it with some element id? Or should I declare it as a JS variable using PHP when I load the page? Or is there a better way?


You can put an attribute on the item itself and retrieve that from the click handler.

<div id="foo" data-item="29"></div>

$(document).ready(function()    {
    $("#foo").click(function(event) {
        bar($(this).data("item"));
    });
});

Of course, if you only have one of these, you don't need to abstract the data number, you can just do it like this:

$(document).ready(function()    { 
    $("#foo").click(function(event) { 
        bar(29); 
    }); 
}); 

But, I think we all assumed that you want the 29 to come from the markup so you can use a common click handler on many elements. If that's the case, then the first method accomplishes that.


Simple - if you're getting the variable using php:

<div id="foo"></div>
$(document).ready(function()    {
    $("#foo").click(function(event) {
        bar( <?= $variable ?> );
    });
});


I would suggest the data-attribute as others have suggested. It's not valid html but It works in all browsers that are used today...
the people who prefer to write valid code(not me in this case) like to add data to the class attribute or will just set it in the javascript.


You could store the parameter as a data attribute:

<div id="foo" data-bar="29"></div>

 

$(document).ready(function()    { 
    $("#foo").click(function(event) { 
        bar($(this).data('bar')); 
    }); 
}); 


Most people think they need parameters to locate elements that are a sub-element of, or an element with a known path from, the element that was clicked. For that kind of thing the best thing to do is not use a parameter at all, but traverse the DOM from the node that was clicked to find the appropriate element.

$("#foo").click(function(event) {
  var doSomethingTo = $(this).find('div')[0];
  doSomethingTo.hide();
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜