正在尝试将元素ID强制转换为jQuery中的类选择器

Trying to cast element ID to class selector in jQuery

本文关键字:jQuery 转换 选择器 ID 元素      更新时间:2023-09-26

这是我的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();
});