Jquery - 如何通过类名传递多个变量?
我想创建一个通用/可扩展的类,它能够接受无变量或多个变量并处理它。我想学习如何检查存在哪个字段、通过的字段数量并对其执行某些操作。 'fruitstall' 类可以接受 0 个或多个水果变量。
HTML:
<div class="fruitstall(apple,orange)"></div>
脚本:
$('.fruitstall').click(function(event){
if (get first variable value and check if it is an apple) {
//Show apple image
} elseif (get the next variable value and check if it is an orange) {
//Show orange image
}
alert('Number of fruit chosen are ' + (count number of variable passed to class) + ' ; ' fruit(index0) + fruit(index1));
});
请原谅我的水果摊例子,我认为以更生动的方式提出问题会很有趣。 :)
非常感谢。
I want to create a generic/scalable class that is able to accept none or multiple variables and process it. I want to learn how to check which field is present, number of field passed and do something with it. The 'fruitstall' class can accept 0 or multiple number of fruits variable.
HTML:
<div class="fruitstall(apple,orange)"></div>
Script:
$('.fruitstall').click(function(event){
if (get first variable value and check if it is an apple) {
//Show apple image
} elseif (get the next variable value and check if it is an orange) {
//Show orange image
}
alert('Number of fruit chosen are ' + (count number of variable passed to class) + ' ; ' fruit(index0) + fruit(index1));
});
Pardon my fruit stall example, I thought it would be interesting to ask question in a more lively method. :)
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一种方法可能是使用 HTML5 数据属性:
然后您的 JS 代码可以这样:
这将获取摊位上所有水果的数组。
Another way might be to use HTML5 data attributes:
Then your JS code could go:
which would get an array of all the fruits for the stall.
您可以分配多个类:
然后像这样对它们进行拆分:
来源:使用 jQuery 获取元素的类列表
You can have multiple classes assigned:
And then do a split on them like so:
Source: Get class list for element with jQuery
我不知道这是否可行,但是如果您将 String 类准备为 JSON 类,您可以使用 eval() 来获取一个对象,您可以从中枚举参数,
我永远不会在生产代码中这样做,但这很漂亮有趣的
干杯
Grooveek
I don't know if that could work, but if you prepare you class String as a JSON one, you could use eval() to get an object from which you could enumerate arguments
I would never do that in production code, but that's pretty funny
Cheers
Grooveek