簡體   English   中英

如何從這個大的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM