Given this HTML:

鉴于此HTML:

<button id="buttonId1" class="hello universe">
<button id="buttonId2" class="hello world">

What's the correct way to do something like this:

做这样的事情的正确方法是什么:

$("#buttonId1").click(function ()
{    
   alert($("#buttonId1").getClass());
}

I realize the getClass function does not exist in JQuery or Javascript. But I'm hoping there's some way to approximate it. I have a more complex real world problem that's difficult to boil down into a simple question but basically I think I need to somehow access the class of an element and then use that class string to perform an additional selection such as this:

我意识到jQuery或Javascript中不存在getClass函数。但我希望有一些方法可以近似它。我有一个更复杂的现实世界问题很难归结为一个简单的问题,但基本上我认为我需要以某种方式访问​​元素的类,然后使用该类字符串执行其他选择,如下所示:

$(("#buttonId1").getClass().filter("world")).hide();

Perhaps there are simpler ways of hiding the buttonId2 in the code I've given - that's not really the point, though. What I'm interested in is how to get at the class and then use that further. The only solution I've come up with so far is use a long branch of if/else statements checking all of the possible classes using the hasClass function. But it's a very inelegant solution.

也许有更简单的方法可以将buttonId2隐藏在我给出的代码中 - 尽管如此,这并不是重点。我感兴趣的是如何上课,然后进一步使用。到目前为止,我提出的唯一解决方案是使用if / else语句的长分支,使用hasClass函数检查所有可能的类。但这是一个非常不优雅的解决方案。

EDIT: Responding to Paolo's answer, perhaps something like this will work to hide button2:

编辑:回应Paolo的回答,也许这样的东西可以隐藏button2:

$(("#buttonId1").attr('class')[0].filter("world")).hide();

3 个解决方案

#1


I think if you try to explain what your ultimate purpose is I might be able to actually help you achieve your ultimate result in the best "jQuery way" - without that, however, all I can say is that:

我想如果你试图解释你的最终目的是什么,我可以真正帮助你以最好的“jQuery方式”实现你的最终结果 - 但是,如果不是这样,我只能说:

$("#buttonId1").click(function() {    
   alert($(this).attr('class'));
});

Would alert 'hello' and:

会警告'你好'并且:

$("#buttonId2").click(function() {    
   alert($(this).attr('class'));
});

Would alert 'hello world'

会提醒'你好世界'

(As a side note, redoing the selector inside an event function like you have in your example is bad practice; you can simply use $(this) to signify the element that is currently being acted upon)

(作为旁注,在您的示例中重做事件函数内的选择器是不好的做法;您可以简单地使用$(this)来表示当前正在执行的元素)

更多相关文章

  1. JavaScript函数中的Ruby代码
  2. jQuery.parseJSON()函数详解
  3. 从内部获取函数名称
  4. Jquery 1.9, JS -函数在Chrome中没有定义
  5. 将php jsonencode数组结果显示为ajax成功函数
  6. 函数的作用是:显示内联块。如何?
  7. 使用jQuery.ajax post函数将javascript数组中的数据传递给服务器
  8. [置顶] JQuery datatables 使用Fixedcolumns固定列控件
  9. TypeError:e。getPosition不是一个函数。

随机推荐

  1. [51CTO]Android消息机制
  2. Android中的动画详解系列【4】——Activi
  3. 解决Android 状态栏重叠
  4. android api 完整翻译之Application Fund
  5. Android EditText 学习笔记
  6. Android市场将持续爆发
  7. Android 手势识别判断,GestureDetector封
  8. Android - 约束布局实现一个简单的登陆界
  9. 我对学习delphiTeacher的《delphi调用及
  10. Android注解:自定义注解之源码注解