jQuery选择器使用usemap属性发现图像

时间:2010-03-28 16:29:39

标签: javascript jquery jquery-selectors imagemap

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

<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 + "]")

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

3 个答案:

答案 0 :(得分:2)

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

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

您应该使用:

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

答案 1 :(得分:1)

尝试引用usemap值的变体:

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

答案 2 :(得分:0)

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的属性。