0

所以我有一个使用 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”是模板的第 4 行。

具有“产品”类的 div 是我希望用户单击的内容,它以 img 为目标并将 img 发送到 showPic。

我希望它使用 jQuery 来定位 .product 。

这是目前的代码。 http://ttrltest.000webhostapp.com/tbcl-products.html

我在回复的帮助下尝试 编辑:

$('.product').click(function(){
    showPic($(this).find('img'));
});

而且我无法从图像元素中获取 src 属性。

4

3 回答 3

0

如果您已经在使用 jQuery,请使用支持 jquery 嵌入事件的 JSON2HTML 的 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}'}
        ]}
    ]}
]}

]};

于 2017-10-30T18:17:52.477 回答
0

alert 或 showPic 都没有被执行,因为你有语法错误。

.children 使用而不用 jquery $() 包装它,评估为属性而不是函数。您可能正在寻找该功能。此外,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'”。不确定从哪里设置内容,但您可能需要仔细检查。

于 2017-06-09T22:57:27.057 回答
0

我找到了答案。

$(this).find('img')产生一个数组,所以我添加[0].src以最终获得源。

于 2017-06-10T00:10:40.207 回答