![](/img/trans.png)
[英]How to get the position of a draggable element in a smaller div and translate that to a large div
[英]How to get image element from this large div element?
所以我有一个使用json2html的代码块模板
var template = {'<>':'div','class':'col-lg-12 col-md-24 col-sm-24 col-xs-24','html':[
{'<>':'div','class':'product col-lg-offset-1 col-lg-22 col-md-offset-0 col-md-24 col-sm-offset-0 col-sm-24 col-xs-offset-0 col-xs-24','html':[
{'<>':'div','class':'prodimg col-lg-8 col-md-8 col-sm-8 col-xs-8','html':[
{'<>':'img','src':'${source}','alt':'${name}', 'class':'img-responsive'}
]},
{'<>':'div','class':'prodetails col-lg-16 col-md-16 col-sm-16 col-xs-16','html':[
{'<>':'span','class':'prodname','html':'${name}'},
{'<>':'div','class':'mT20','html':[
{'<>':'p','html':'${info1}'},
{'<>':'p','html':'${info2}'},
{'<>':'p','html':'${info3}'}
]}
]}
]}
]};
粗体部分是我要运行功能showPic(img);的图像; 其中“ img”是模板的第四行。
带有“产品”类的div是我想要被用户单击的对象,它以img为目标并将img发送到showPic。
我希望它使用jQuery定位.product。
现在的代码如下。 http://ttrltest.000webhostapp.com/tbcl-products.html
我试着在回复的帮助下进行编辑 :
$('.product').click(function(){
showPic($(this).find('img'));
});
而且我无法从image元素获取src属性。
因为存在语法错误,所以警报或showPic均未执行。
不用将其包装在jquery $()中的.children评估为属性而不是函数。 您可能正在寻找该功能。 另外,children函数仅返回直接的children,看着您的图像,它们是DOM中的几个元素。 使用find()代替。
$(".product").click(function(){
showPic($(this).find('img'));
});
编辑
在纯Javascript和Jquery之间切换时要小心。 现在,您正在showPic方法内部使用JQuery对象。 更新您的方法:
function showPic(img){
content.innerHTML = "<img src='" + $(img).attr("src") + "' alt='' class='img-responsive center-block'>";
modal.style.display = "block";
}
注意:我在您的网站上尝试了showPic方法,但出现错误“无法设置未定义的属性'innerHTML'”。 不确定从哪里设置内容,但是您可能需要仔细检查。
我找到了答案。
$(this).find('img')
产生一个数组,所以我添加了[0].src
以最终获得源代码。
如果您已经在使用jQuery,请使用JSON2HTML的jquery插件,该插件支持jquery嵌入式事件。 您可以通过以下方法将onclick属性直接添加到转换中,这样以后就不必使用jquery添加它了
var template = {'<>':'div','class':'col-lg-12 col-md-24 col-sm-24 col-xs-24','html':[
{'<>':'div','class':'product col-lg-offset-1 col-lg-22 col-md-offset-0 col-md-24 col-sm-offset-0 col-sm-24 col-xs-offset-0 col-xs-24','html':[
{'<>':'div','class':'prodimg col-lg-8 col-md-8 col-sm-8 col-xs-8','html':[
{'<>':'img','src':'${source}','alt':'${name}', 'class':'img-responsive'}
],'onclick':function(){
//do whatever you need to here, like find your image etc..
var $img = $(this).find('img');
}},
{'<>':'div','class':'prodetails col-lg-16 col-md-16 col-sm-16 col-xs-16','html':[
{'<>':'span','class':'prodname','html':'${name}'},
{'<>':'div','class':'mT20','html':[
{'<>':'p','html':'${info1}'},
{'<>':'p','html':'${info2}'},
{'<>':'p','html':'${info3}'}
]}
]}
]}
]};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.