开发者

Getting the src attribute of a child element (child to <a>) in an iFrame and return it to the parent using javascript

Since it's an iframe generated dynamically out of php and it just contains a list of pictures I want to get the src attribute of the clicked item (an image wrapped in an anchor tag) and return that to the parent or save it to a variable that can later be accessed by the parent.

The thing is jQuery is in the parent window, not the iframe itself so I have to use pure javascript and find a way to send the variable back to the parent. I've tried:

function(){
                $('#fancybox-frame').contents().find('.clickable').click(function(){
                    alert('hey');
                });

from the parent window but it just doesn't work, so what I have now is an inline onclick event in the anchor of the image:

onClick=\"alert('this does work')\"

how can I manage to get the child's src attribute and send it back to the parent?

EDIT

I've also tried seve开发者_如何学编程ral variations of this:

onclick=\"this.className += 'pickedOne';\"

but I haven't been able to get it to set correctly.

All the elements inside the iframe have the following structure:

<div style=\"width: 300px; height:300px; float: left; margin-right:10px; \"><a onclick=\"this.className += 'pickedOne';\" title='".$value."' href='#'><img class='clickable' src=\"" . $value . "\" border=\"0\"/></a></div>


The way you did it with jQuery is ok, I have a web application that works the same way. jQuery is loaded in the parent window, and the events get fired inside the iframe using the same method you used.

Probably you used the wrong ID or class as a selector.

Also, make sure you are waiting for the content of the iframe to be loaded before trying to attach any event listener.

$('#fancybox-frame').load(function() {

    $('#fancybox-frame').contents().find('.clickable').click(function(){
        alert('hey');
    });

});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜