开发者

clicking multiple elements at same time, what is 'this'

I feel like there must be a much better way of expressing the following condition:

if(node.is('a') || node.parent().is('a')){
        foo
    }

I want this for elements that are wrapped in an anchor tag, and to be able to easily retrieve/manipulate the href when it's the direct target or the parent.

<a href="#"><img src="#" /></a>

When clicking the image as expressed above, the event seems to be 开发者_开发技巧only grabbing just the <img> and not the <a> wrapping it. I want to be able to play with both from a single click.

More detail on what I'm doing: trying to make an interface that allows you to click to inline-edit certain text areas (some of which have links around them) and images. I have an .editable class that i'm listening for. I have it working with regular links and text; trying to figure out how to get image uploads going. more code


var $img = $(this)
,   $a   = $img.parent('a');

if($a.length) {
    //Do stuff if img is in anchor
}

If there is no anchor the length will be 0. Here is a jsfiddle to demonstrate it http://jsfiddle.net/Akkuma/2UMvj/

The alternative is to put the click on all a, but I'm assuming you need this logic only when an img is clicked.

If you need the code to fire off only when an img inside of an a is clicked you could do this

$('a').delegate('img', 'click', function () {
    var $img = $(this)
    ,   $a   = $img.parent();
});

An example of this is http://jsfiddle.net/Akkuma/BS54P/


You can grab both by attaching click event to your link, from parent you can filter down to child. Like so...

$('a').click(function(){
    var thilink = $(this).attr('href');
    var thiscontent = $(this).html();
});

EDIT

Or if image is object of concern, which function above, you can add,

    var thisimg = $(this).find('img');
    \\then you can access any number of properties including src and manipulate them via
    var currentsrc = thisimg.attr('src');


function whoGotClicked(who){
if (node.is("a"))
     alert("im an anchor");
    else
        alert("im a"+node.get(0).tagName);

}

$("img").click(function(e){
    node=$(this).parent();
    whoGotClicked(node);
    return false;
});

here is the fiddle http://jsfiddle.net/LZxRd/2/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜