2013-10-08 45 views
0

我有被设定为一个变量如何通过一个变量/和在JavaScript的onclick功能

var imagepath = "../Resources/Images/teamLogo1.png"; 

现在的图像我要通过这个作为一个参数的点击一些路径参数的的onclick功能

请检查fiddle here

我追加的形象和我需要写的onclick功能有 编辑: 包括完整的代码

$(document).ready(function(){ 
var imagepath = "../Resources/Images/teamLogo1.png"; 
    $("#Testing").append('<img src="http://www.magerempowerment.com/v2/blog/wp-content/uploads/2012/07/doubt_dice.jpg" onClick="testfunction('+ imagepath + ')">'); 

}); 

function testfunction(imagepath){ 
alert(imagepath); 
}; 
+0

请在此复制相关代码;现在人们需要看到小提琴完全了解你所问的。 –

+0

好的代码中添加了!谢谢 –

回答

1

不要在HTML代码嵌入不处理的。

$(document).ready(function(){ 
    var imagepath = "../Resources/Images/teamLogo1.png", 
     img = $('<img src="http://.../doubt_dice.jpg">'); 
    img.click(function() { 
     // you can refer to imagepath here, for example 
     $(this).prop('src', imagepath); 

     // or call your function: 
     testfunction.call(this, imagepath); 
    }); 
    img.appendTo("#Testing"); 
}); 

但请注意,相对路径("../Resources/Images/teamLogo1.png")总是相对于HTML文档。

+0

太棒了!谢谢 http://jsfiddle.net/vEFWq/3/ –

1

由于该值是一个字符串,你需要''

$(document).ready(function() { 
    var imagepath = "../Resources/Images/teamLogo1.png"; 
    $("#Testing").append('<img src="http://www.magerempowerment.com/v2/blog/wp-content/uploads/2012/07/doubt_dice.jpg" onClick="testfunction(\'' + imagepath + '\')">'); 

}); 

function testfunction(imagepath) { 
    alert(imagepath); 
}; 

演示给它括:Fiddle

1

使用.prop

$('img').click(function(){ 
    alert($(this).prop('src')); 
}); 
1

你的功能将无法通话,因为你正在创建img dynamically,所以试试吧,

HTML

$("#Testing").append('<img src="http://../doubt_dice.jpg" data-path="'+imagepath+'">'); 

SCRIPT

$(document).on('click','img',function(){ 
    console.log($(this)); 
    alert($(this).data('path')); 
}); 

Fiddle

相关问题