首页 > 解决方案 > Javascript - 单击侦听器未传递所有数据

问题描述

我有几个包含图像、文本和链接的 div。它们由 .feed-item 类标识。我不想只通过点击链接访问后面的链接,我想让整个 div 可点击。

我可以通过 DIV 级别的 onclick 轻松解决此问题,但现在我使用的是 AMP,我不再允许在 DIV 中使用 onclick,因此我尝试使用侦听器找到解决方案。

站点为:https ://www.laurentwillen.be 关注类:.feed-item 源码:

<div class="feed-item page-1" data-page="1" >
    <div class="feed-image"><amp-img class="amp_img" src="www.laurentwillen.be/pixel.gif"  width="160px" height="50px"  sizes="calc(20vw - )" srcset="https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-300x94.jpg 300w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-768x240.jpg 768w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-1024x319.jpg 1024w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-1400x437.jpg 1400w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-900x281.jpg 900w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-700x218.jpg 700w, https://www.laurentwillen.be/wp-content/uploads/sites/21/2019/01/avis-review-aliexpress-500x156.jpg 500w" alt="avis-review-aliexpress"></amp-img></div><div class="feed-category">Expérience d'achat</div>
    <div class="feed-text">
        <div class="feed-title">Mon avis complet sur Aliexpress.com</div>
        <div class="feed-link"><a href="https://www.laurentwillen.be/experience-dachat/mon-avis-complet-sur-aliexpress-com/">Mon avis complet sur Aliexpress.com</a></div>
        <div class="feed-description">J'ai acheté plus de 90 produits sur Aliexpress et je partage mes bonnes et mauvaises expériences pour vous aider à choisir.</div>
    </div>

我的代码:

feed_item = document.getElementsByClassName('feed-item');
for (a=0;a<feed_item.length;a++)
{
        feed_item[a].addEventListener("click", function(e){
        console.log(e.target.innerHTML);
        parser = new DOMParser();
        var local_html = parser.parseFromString(e.target.innerHTML, "text/html");
        link = local_html.querySelectorAll('div.feed-link a');
        console.log(link[0]);
        //document.location = link[0];
    });
}

如果我单击 DIV 边框,我会在 div 中获得完整的 HTML,然后我可以解析它以检索链接。如果我单击 DIV 内的任何位置(例如:在描述文本上),我只会获得链接不可用的特定区域的 HTML。我想获取 .feed-item 中的所有 html 而不是一些子 DIV。

你知道我怎么能做到这一点吗?它必须是香草JS。

标签: javascriptonclicklisteneramp-html

解决方案


要“使整个 div 可点击”,您可以将 A 放在您的 DIV 上:

<a href=...>
    <div class="feed-item ...>

您不能在 AMP 中使用脚本。如果您从 AMP 开始,请经常在https://validator.ampproject.org/尽早验证您的页面。它将帮助您远离 AMP 中的所有限制!


推荐阅读