开发者

jQuery selector issue finding image with usemap attribute

I have an image map in my page:

<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>

I have a function that tries to find the image in开发者_如何学JAVA the document using this map:

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);
    }
}

It fails to find the image.

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

I've escaped the elemId because it starts with a hash and tried variations of selectors.

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

Neither find the image. Any ideas?


You have a space between img and [usemap=\#map_books].

That results in an attempt to match a child element of img with an attribute usemap set to #map_books.

You should use:

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


Try variations on quoting the usemap value:

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


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);
        }
    }
}

You had an extra space between img and [] for getting to the img's attributes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜