【问题标题】:jQuery selector for all <img> in a div if class includes a certain string如果类包含某个字符串,则 div 中所有 <img> 的 jQuery 选择器
【发布时间】:2021-06-06 21:52:07
【问题描述】:

我希望能够使用一个 CSS 选择器同时选择这两个:

<div id= "someID">
  <img src="images/leave-alone.png" class= "leave-alone">
  <img src= "images/source.png" class= "foo bar">
  <img src= "images/other-source.png" class= "foo zip">
</div>

理想情况下,类似“class includes 'foo'”这样的内容可以同时捕获这两个图像。我知道我可以使用两次.children().last().remove(),但我想确保我的代码比这更动态。

编辑:意识到我是通过单击来完成此操作的,因此我希望能够以$(this) 作为我的 jQuery 起点来实现相同的目标。

编辑:我用$("#" + $(this).attr("id") + " img.foo").remove() 破解了它,但也许还有更优雅的东西。

【问题讨论】:

  • document.querySelectorAll("#someID img.foo")
  • $("#someID img.foo) 或 $('img.foo")

标签: javascript jquery image class dom


【解决方案1】:

您可以尝试使用class foo 选择所有图像

$("img.foo") 

或者像这样在带有id someId的div下选择带有class foo的图像

$("#someID img.foo")

【讨论】:

  • 如果我以 $(this) 开头怎么办?
【解决方案2】:

你可以试试$('img[class~=foo]')

Advanced selectors 很棒。这是源链接。

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 2011-05-05
    • 2011-01-22
    • 2014-03-22
    • 2019-06-25
    • 1970-01-01
    • 2011-12-28
    • 2012-09-30
    相关资源
    最近更新 更多