开发者

jQuery use child click/attribute in parent

Why this does not work in IE/Chrome but works in FF/Opera? I want to make the div around anchor clickable, so that when you click div, it behaves the same as if you would click the anchor itself.

<script src="jquery-1开发者_JS百科.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function bindOnClickPostBack() {
        $(".header a").each(function () { 
            var anchor = $(this);
            var clickEvent = anchor.attr('href');
            var header = anchor.parent();
            header.css('background-color', 'yellow');
            header.attr('onclick', clickEvent);
        });
        /*$(".header").live("click", function(){
            anchor = $(this).find('a');
            var clickEvent = anchor.attr('href');
            alert(clickEvent);
            $(this).css('background-color', 'yellow');
            //header.attr('onclick', clickEvent);
            //anchor.click();
        });*/
        return false;
    }

    $(document).ready(function() {
        bindOnClickPostBack();
    });
</script>

body:

<div style="background-color:red" class="header"> <a href="alert('hello1')">Shortcut1</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello2')">Shortcut2</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello3')">Shortcut3</a></div>
<div style="background-color:red" class="header"> <a href="alert('hello4')">Shortcut4</a></div>


Um... why would you want to do that? If you want the whole header to be clickable, just make a big block-level anchor:

<a href="#" class="header">Big Header</a>

with:

a.header { display: block; width: 100%; height: 50px; background: yellow; }

and

$("a.header").click(function() {
  // do stuff
  return false;
});

or maybe the href is enough in this case.

If you really want to go down the route you are (and I would recommend against it), you need to find out what's in the href attribute. Different browsers might be massaging it somewhat.

The more normal way to bind a click event is:

$("div.header").click(function() {
  // do stuff
});

not mess with the onclick attribute directly.

Alternatively you could do:

$("div.header").click(function() {
  return $("a". this).click();
});

but again: why not just make the anchor large enough to be the header, making it a block level element if necessary?


Since you're using jquery, try this:

$(document).ready(function() {
    $('div.header').click(function() {
       $(this).find('a').click();
    });
});


+1 for cletus' answer, but I'll also add - event delegation.


Tried to do the same, a link in a list element. To produce a click on the A tag, inside the LI or header element tag makes a "too many recursions" error. Indeed, like Cletus said, making the A as a block element instead of inline makes the deal.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜