【问题标题】:jQuery selector issue finding image with usemap attribute使用 usemap 属性查找图像的 jQuery 选择器问题
【发布时间】:2010-03-29 00:36:16
【问题描述】:

我的页面中有一张图片地图:

<div id="books">
  <img src="images/books.png" width="330" height="298" border="0" \
   usemap="#map_books" />
  <map name="map_books" id="map_books" alt="books">
    <area shape="poly" coords="17,73,81,288,210,248,254,264, ..." \ 
     href="/about" alt="books" />
  </map>
</div>

我有一个函数尝试使用此地图在文档中查找图像:

function(elemId) { // elemId = "#map_books"

  if ($(elemId).attr("tagName") == "MAP") {
    // find image using this map
    var selector = "img [usemap=\\" + elemId + "]"; 
    var img = $(selector);

    if (img.length == 0) {
      console.log("Could not find image using " + selector);
    }
}

找不到图片。

Could not find image using img [usemap=\#map_books]

我已经避开了elemId,因为它starts with a hash 并尝试了选择器的变体。

$("img [usemap$=" + elemId.substring(1) + "]")
$("img").find("[usemap=\\" + elemId + "]")

找不到图片。有什么想法吗?

【问题讨论】:

  • 另外,避免比较tagName 区分大小写,因为不能保证浏览器会将其大写。 attr('tagname' 也是有问题的,因为 tagName 不是 HTML 属性。它恰好起作用,因为 jQuery 将大多数属性访问重定向到属性访问,但我认为 $(elemId)[0].tagName.toLowerCase()==='map' 是一个更好的测试。
  • $(elemId) 是一个集合,将始终拥有$(elemId][0]?

标签: javascript jquery jquery-selectors imagemap


【解决方案1】:

img[usemap=\#map_books] 之间有一个空格。

这会导致尝试将img 的子元素与设置为#map_books 的属性usemap 匹配。

你应该使用:

var selector = "img[usemap=\\" + elemId + "]"; 

【讨论】:

    【解决方案2】:

    尝试引用 usemap 值的变体:

    $("img[usemap='#whatever']");
    $('img[usemap="#whatever"]');
    

    【讨论】:

    • 与引用无关。根据文档:api.jquery.com/category/selectors 他对哈希的转义是正确的,并且根据该特定选择器的文档:api.jquery.com/attribute-equals-selector 引号是完全可选的
    • 既然这也行得通,我会给你一个赞成票,但我要把它授予 Dancrumb。
    • 之所以有效,是因为@John 删除了您的流氓空间并添加了引号
    • 是的,我知道您现在已经解释过了。谢谢
    【解决方案3】:
    function(elemId) { // elemId = "#map_books"
    
        if ($('map'+elemId).length) {
            // find image using this map
            var selector = "img[usemap=\\" + elemId + "]"; 
            var img = $(selector);
    
            if (img.length == 0) {
                console.log("Could not find image using " + selector);
            }
        }
    }
    

    你在 img 和 [] 之间有一个额外的空间来获取 img 的属性。

    【讨论】:

    • 谢谢,您只比其他人落后几分钟,提供了正确答案。
    猜你喜欢
    • 2018-10-30
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-28
    • 2015-12-08
    • 1970-01-01
    相关资源
    最近更新 更多