简体   繁体   English

如何在JavaScript onclick函数中使用/作为参数传递变量

[英]how to pass a variable with / as a parameter in javascript onclick function

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 现在点击图片,我必须将其作为参数传递给它的onclick函数

Please check the fiddle here 请在这里检查小提琴

I am appending the image and i need to write onclick function there EDIT: Including the full code 我要附加图像,并且需要在其中编写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);
};

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 使用.prop

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

Your function will not call because you are creating img dynamically so try it like , 您的函数不会调用,因为您是img dynamically创建img dynamically因此请尝试使用,

HTML 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 小提琴

Do not embed handlers in HTML code at all. 根本不要在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");
});

Notice however that the relative paths ( "../Resources/Images/teamLogo1.png" ) are always relative to the HTML document. 但是请注意,相对路径( "../Resources/Images/teamLogo1.png" )始终相对于HTML文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM