【问题标题】:How can I target a specific list item that has the same class as all other list items如何定位与所有其他列表项具有相同类的特定列表项
【发布时间】:2013-10-09 15:23:53
【问题描述】:

好的,所以我的脚本允许我在 textarea 元素中输入文本并将其添加到 ID 为“Glist”的有序列表中的 li 元素中。我添加到有序列表中的每个 li 不仅添加了文本,而且还添加了下面的其他内容,它们都只是使用 CSS 显示额外的图像。其中一个类“Selimg”显示了一个按钮的精灵图像,上面写着“选择”。现在,我添加到我的 ol 中的每个 li 元素都具有以下所有元素以及类。因此,每个 li 元素都有一个带有“Selimg”类的 div,该类显示一个按钮的图像,例如选择。当我单击带有类 Selimg 的这个 div 时,一个名为“Selected”的新类将添加到 div 中,这将改变 li 的背景颜色以指示它已被选中。问题是,我只想将“Selected”类添加到带有我单击的 Selimg 类的 div 中,而不是所有带有“Selimg”类的 li 元素。如何使用 onclick 事件处理程序或使用 js 或 jquery 的任何其他方式来做到这一点?这是html:

<ol id="GList">
<li class="MyList">
<p class="bulletp"></p>
<!--This Selimg class displays an image of a button that says select-->
<div class="Selimg"></div>
<!--When a user presses this select button, I want to append a class only to the   specific li element the user has pressed the select button on. -->
<div class="edit1"></div>
<div class="Del"></div>
<div class="progress"></div>
<div class="ShowMore"></div>
<div class="CheckedGoal"></div>
<div class="PCompetePercent"></div>
<div class="ShowMoreBlock"></div>
<div class="goalTxt"></div>
</li>
</ol>

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    点击按钮,可以使用.closest()查找祖先li元素

    $('.Selimg').click(function(){
        $(this).closest('li').addClass('someclasss')
        //or $(this).parent().addClass('someclasss') since the li is the parent of the button
    })
    

    演示:Fiddle

    【讨论】:

    • 啊,真的。谢谢。但现在的问题是它们都可以被选中。一旦我选择了另一个 li 项目,我怎么能做到这一点,所有其他 li 元素都不会被选中。我想我知道一种方法,但我相信有一个我没有想到的更简单的解决方案。对不起,我没有在我的帖子中包含这个。直到我尝试了你的小提琴,我才想到它。
    猜你喜欢
    • 2014-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-04-09
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2011-10-22
    相关资源
    最近更新 更多