显示一个按钮,并只针对特定的li元素划掉

show a button and strike through only for that particular li element

本文关键字:li 元素 一个 按钮 显示      更新时间:2023-09-26

我有以下代码,它工作得很好,除了当涉及到可能嵌套在LI元素下的嵌套LI元素时,我的目标:

$('#comment-section .comment-box a#un-do').hide();
$('#comment-section ul li[data-is-archived="true"]').map(function() {
  $('#comment-section ul li[data-is-archived="true"]').css('text-decoration', 'line-through');
  $('#comment-section ul li[data-is-archived="true"] a#un-do').show();
}).get();

这将删除此li元素中的任何文本,并显示与此特定元素(或集合)匹配的每个li元素的撤消链接。

ul
 li - strike through works, shows undo button, data-is-archived = true
  ul
   li - strike through works, shows undo button, data-is-archived = false

为什么每个嵌套的li元素都被划掉并有一个链接出现,而只有那些具有data-is-archived=true的元素应该被划掉并且链接显示为代码状态?

这是因为text-decoration: strike-through属性适用于<li>元素中具有值true的HTML5数据属性is-archived的所有文本,无论嵌套的子元素是否适合选择器。我已经在JSfiddle中复制了您的问题(下次请自己这样做):http://jsfiddle.net/teddyrised/TZVej/1/

解决方案是将每个<li>元素中的文本用<span>元素包裹起来,并通过限制性的,仅限直接继承的CSS来应用。

$('#comment-section .comment-box a#un-do').hide();
$('#comment-section ul li[data-is-archived="true"]').map(function() {
    // Target only <span> elements that are direct descendants
    $('#comment-section ul li[data-is-archived="true"] > span').css('text-decoration', 'line-through');
    $('#comment-section ul li[data-is-archived="true"] a#un-do').show();
}).get();

在这里查看概念验证:http://jsfiddle.net/teddyrised/TZVej/2/

p/s:我不知道为什么你在问题的上下文中使用.map()函数…