正在尝试将元素ID强制转换为jQuery中的类选择器
Trying to cast element ID to class selector in jQuery
这是我的jsfiddle:
http://jsfiddle.net/fk434/
代码:
$('.theHider').click(function () {
$("'." + $(this).id + "'").hide();
});
HTML:
<div class="cola">This will be cola</div>
<div class="cola">This will be cola</div>
<div class="birch">This will be birch</div>
<div class="cola">This will be cola</div>
<div class="cola">This will be cola</div>
<div class="orange">This will be orange</div>
<div class="birch">This will be birch</div>
<div id="cola" class="theHider">This will hide cola</div>
<div id="birch" class="theHider">This will hide birch</div>
<div id="orange" class="theHider">This will hide orange</div>
我不明白为什么这不起作用。
至于文档准备等,当它阻止jsfiddle工作时,我把它拿了出来。
id
是DOM元素本身的属性,而不是jQuery包装器,因此它应该是this.id
,而不是$(this).id
。你还有一些多余的引号需要删除:
$('.theHider').click(function () {
$("." + this.id).hide();
});
是你的引号阻止了它的工作,选择器无效。试试这个:
$('.' + this.id).hide();
没有字段$(selector).id
,您将javascript元素与这个jquery元素混合在一起。
试试这个:
$('.theHider').click(function() {
var selector = "."+$(this).prop("id");
$(selector).hide();
});
这里的问题是在选择器中插入了太多引号。
$( "'." + this.id + "'" ).hide();
// ^----------------^------ these are not needed
你不必添加单引号-只需正常构建选择器-
$( "." + this.id ).hide();
这是你的小提琴的固定版本
当你遇到问题时,一定要检查你的JavaScript控制台。对于您的原始代码,在与您正在构建的选择器相同的行上出现了以下错误:
未捕获错误:语法错误,无法识别的表达式:".cola"
这将解决问题:
$('.' + this.id)
然而,我想提请您注意数据属性:
<div class="theHider" data-tohide="cola">This will hide cola</div>
这允许您在需要时将标识符用于其他内容;点击处理程序如下所示:
$('.theHider').on('click', function() {
$('.' + $(this).data('tohide')).hide();
});
相关文章:
- js代码从jQuery转换为原生代码
- 将jQuery转换为用户脚本的普通Javascript时遇到问题
- 将jquery转换为javascript,以便能够在greatemonkey上运行
- 将简单的jQuery转换为JavaScript
- 将 jQuery 转换为等效的 JavaScript 代码
- 抓取表数据并使用jQuery转换为无序列表
- 将jQuery转换为Angular,固定侧边栏不起作用(?)
- 将 Jquery 转换为角度或使 Jquery 以角度工作
- 将函数从jQuery转换为Mootools
- jQuery 转换未完成
- 如何使用jQuery转换所有带有动态类的内联样式css
- 我怎样才能把它从jQuery转换为vanilla JS
- 将 Jquery 转换为 Motools
- 带有nav元素的jQuery转换的Javascript
- 将jquery转换为Angularjs
- jQuery转换的代码不起作用
- 如何将函数从Jquery转换为Javascript
- 引导程序'选择'样式,使用jquery转换为bootstrap下拉列表
- 将代码从jquery转换为纯javascript
- 将JQuery转换为JavaScript