0

I am trying to do a .each function to push an impression for each product on a search results page into a dataLayer. I am having a hard time figuring out how to specify the $(this) element in my foreach. I am not sure this is best way to do what I want, so if anyone has a better way of doing this, please let me know :)

Hope I am making sense! Thanks!

<script>
 $(function () {
            $(".result-price-carpark-name span, .result-price-actual").each(function(index) {
            console.log( index + ": " + $( this ).text() );
            var carpark = $(this).text(); //How to specify its $(this) inside the .result-price-carpark-name span??
            var price = $(this).text(); //How to specify its $(this) inside the .result-price-actual??
            
             dataLayer.push({
            'ecommerce': {
            'currencyLocal': 'USD',
            'impressions': [{
            'name': carpark,
            'id': carpark,
            'price': price,
            'category': carpark,
            'list': 'ParkAstro',
            'position': ''
            }]
            }
            })
            })
        });

</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result-prices-item">
<div class="result-price-carpark-name"><span>PARK1</span></div>
<div class="result-price-actual">22</div>
</div>

<div class="result-prices-item">
<div class="result-price-carpark-name"><span>PARK2</span></div> 
<div class="result-price-actual">22</div>
</div>

<div class="result-prices-item">
<div class="result-price-carpark-name"><span>PARK3</span></div> 
<div class="result-price-actual">22</div>
</div>

4

1 回答 1

0

如果您想遍历每个停车场项目,那么您需要遍历每个停车场项目(即,不是孩子)。然后,在该循环中,您可以使用可选的context 参数获取子项(也就是该特定项目的名称和价格)。

$(".result-prices-item").each(function() {
    $('.result-price-carpark-name', this).text();
    $('.result-price-actual', this).text();
});

等等

于 2015-07-05T10:51:28.990 回答