2

当我单击图像时,我想将该特定图像存储src在 Javascript 变量中。我怎样才能做到这一点?请记住,<a>标签用于悬停效果。因此,当我单击时,<a>我想要其兄弟姐妹的图像源。

演示:http: //jsfiddle.net/FVrTg/2

<div>
    <img src = "http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg"/>
    <a href = "#"></a>
</div>

<div>
    <img src = "http://whatiscat.com/wp-content/uploads/2011/07/cute_cat_2.whatiscat.com_.jpg"/>
    <a href = "#"></a>
</div>

​</p>

4

4 回答 4

2
$("a").on("click", function() {
    alert ( $(this).siblings("img").attr("src") );
});

演示

...

更新

仅限 JS - http://jsfiddle.net/FVrTg/7/

var links = document.getElementsByTagName("a");
var size  = links.length;

for ( var i = 0; i < size; i++ ) {
    links[i].addEventListener("click", function() {
        alert( this.previousSibling.previousSibling.getAttribute("src") );
    }, false);
}
于 2012-07-01T23:53:27.673 回答
0

这是一种将打印img.src输出rel="img-id"用于将 与 相关联的a方法img

HTML

<div>
    <img id="img-1" src="http://upload.wikimedia.org/wikipedia/commons/thumb/2/26/YellowLabradorLooking_new.jpg/260px-YellowLabradorLooking_new.jpg"/>
    <a href="#" class="img-hover" rel="img-1"></a>
</div>

Javascript

window.onload = function(){
    var links = document.getElementsByTagName('a'),
        c_links = links.length,
        link;

    while (c_links--){
        link = links[c_links];

        if (link.className.indexOf('img-hover') > -1) {
            link.onclick = function(){
                var img = document.getElementById(this.rel);

                if (img) {
                    console.log(img.src);
                }
            };
        }
    }
};

http://jsfiddle.net/userdude/ecXCX/

于 2012-07-02T00:15:30.043 回答
0
$('a').click(function(e){
   e.preventDefault();
   var src = $(this).siblings('img').prop('src');
})

http://jsfiddle.net/FVrTg/5/

于 2012-07-01T23:52:14.567 回答
0

使用委托事件clickon document,以提高效率,并获取parentNodefor <a>。然后抓住<img>并得到src。您可以安全地添加到parentNode您的设计中,而无需更改代码。

演示:http: //jsfiddle.net/ThinkingStiff/NWD7f/

document.addEventListener( 'click', function( event ) {

    var a = event.target;

    if( a.tagName.toLowerCase() == 'a' ) {

        var src = a.parentNode.getElementsByTagName( 'img' )[0].src;
        console.log( src );

    };

}, false );​
于 2012-07-02T00:10:26.863 回答