I have some path which is set to a variable
var imagepath = "../Resources/Images/teamLogo1.png";
Now on click of an image I have to pass this as a parameter in its onclick function
Please check the fiddle here
I am appending the image and i need to write onclick function there EDIT: Including the full code
$(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);
};
Since the value is a string, you need to enclose it with ''
$(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);
};
Demo: Fiddle
Use .prop
$('img').click(function(){
alert($(this).prop('src'));
});
Your function will not call because you are creating img dynamically
so try it like ,
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'));
});
Do not embed handlers in HTML code at all.
$(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");
});
Notice however that the relative paths ( "../Resources/Images/teamLogo1.png"
) are always relative to the HTML document.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.