定位提示确认的img

时间:2014-06-06 20:15:30

标签: javascript jquery html image title

所以我要做的是在鼠标点击时从动态添加的<img>中提取信息。 它总是以未定义的形式返回....我的代码:

for (i=0; i<x.length; i++) {
    var objectElem = x[i];
     var a = (objectElem.getElementsByTagName("source")[0].textContent),
         b = (objectElem.getElementsByTagName("artist")[0].textContent),
         c = (objectElem.getElementsByTagName("title")[0].textContent),
          num = (objectElem.getElementsByTagName("vote")[0].textContent), 
         par = '<img class="item" href="#" ondblclick="confirmed()" src="'+ a +'" title="' +b+ ' - '+ c+ '" />';
     console.log(par);
     document.getElementById("add").innerHTML += par;
}

function confirmed() {
    targ = (this.title);
    console.log(targ);

    var bools = confirm("Is This Your choice?");
    if(bools == true){
        y=1;
        adds = (++y)
        tote = (num+adds)
        txt=(targ);

    }else{
     txt = "You hit cancel";
    }
    document.getElementById("demo").innerHTML = txt;    
}

不确定原因,感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

由于您对jQuery解决方案持开放态度,请在关注注释的同时查看以下代码段:

$( document ).ready(function () {

    // Init images (note: This should preferably be done server side if you're parsing xml)
    for (i=0; i < 10; i++) {
        var a = "http://lorempixel.com/100/100/technics/album-" + i,
            b = "Artist_" + i ,
            c = "Title_" + i,
            num = i,
            par = '<img class="item" href="#" src="'+ a +'" title="'+ b +' - '+ c +'" data-num="'+ i +'" />';
        console.log(par);

        document.getElementById("add").innerHTML += par;
    }

    // Tip: Double Click binding to the img with 'item' class (better than having it inline on the tag)
    $("body").on("dblclick", "img.item", function (e) {
        e.preventDefault(); // not really needed in this case since the default double click on an image does nothing by default, but good to know you can prevent default actions

        var $img = $(this);

        confirmed($img);
    });


    // Important: Notice that we're passing the trigger element (in this case it's the image) to the confirmed function.

    function confirmed($img) {
        var targ = $img.attr("title");
        console.log(targ);

        var confirmation = confirm("Is '" + targ + "' your choice?");
        if (confirmation) {
            y=1;
            adds = (++y)
            tote = (num+adds)
            txt=(targ);

        } else {
            txt = "You hit cancel";
        }

        // $("#demo").html(text) <-- jquery way
        document.getElementById("demo").innerHTML = txt;  
    }
});

我希望这会有所帮助。

jsFiddle Demo