作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这个:
jQuery(document).ready(function(){
jQuery('a.color2030').click( function() {
jQuery('tbody').hide();
jQuery('tbody.color2030').show();
});
jQuery('a.color2031').click( function() {
jQuery('tbody').hide();
jQuery('tbody.color2031').show();
});
...
...
jQuery('a.color2037').click( function() {
jQuery('tbody').hide();
jQuery('tbody.color2032').show();
});
});
但不想为每个链接重复代码块。我可以通过任何方式从链接中获取 id。可能是 color2030 等。
我已经尝试过:
<a href="#color2030" class="color2030" id="test2030">
<a href="#color2031" class="color2031" id="test2031">
<a href="#color2032" class="color2032" id="test2032">
在 jQuery 中:
jQuery('a').click(function() {
// this works
var id = 'test';
alert(id); // will alert 'test'
// this does not work
var id = $(this).attr('id'); //update2: should have been jQuery(this...
alert(id); // no alert but error on page
});
但我似乎无法掌握该 ID。 “var id”行似乎有错误左右。是否有另一种方法可以在按下时从 a 标签读取 id/class 或其他标签?
BR。安德斯
更新:由于两个人发现的拼写错误不超过 30 瑞典克朗!
更新2并解决!我无法发现的错误是 $(this) ,它应该是 'var id' 行中的 jQuery(this)
最终更新解决方案这是正在做的伎俩
jQuery(document).ready(function(){
jQuery('a').click( function() {
var id = this.id;
alert(id);
jQuery('tbody').hide();
jQuery('tbody.'+id).show();
});
});
最佳答案
onclick
应为 click
:
jQuery('a').click(function() {
var id = $(this).attr('id');
alert(id);
});
关于jquery,从单击的项目中获取 id/class/other 并重用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1910802/
我是一名优秀的程序员,十分优秀!