pg. pg. - 6 months ago 12
Javascript Question

Loop through an object in a page, if page contains key, append value

I have a page full of links. I want to put a little jquery at the bottom that looks for particular URL's or and for each one, append a little tag at the bottom of the page if it finds that URL in the content or if the current page's canonical link (which is included in the meta) matches. So far I have this:

<script type="text/javascript">
var obj = {
"apple.php":"apple_pixel_url",
"banana.php":"banana_pixel_url",
"carrot.php":"carrot_pixel_url"
};

$.each( obj, function( key, value ) {
$( "html:contains(key)" ).append('<img src="'+value+'">');
});
</script>


This always appends all three values, so I'm obviously doing something wrong. I guess Ideally I would look at only "a" links plus any tags that matched

<link rel="canonical" href="CANONICAL_URL" />


What is the best way to do this?

Answer

It always appends the three links because it's finding the values in your javascript! You should put the javascript in <head>, then only check for links within <body>.

var obj = {
    "apple.php":"apple_pixel_url",
    "banana.php":"banana_pixel_url",
    "carrot.php":"carrot_pixel_url"
};
function load(){
  $.each( obj, function( key, value ) {
      $("body:contains("+key+")").append('<img src="'+value+'">');
  });
}

<body onload="load()">
    apple.php
    carrot.php
</body>

Here's a fiddle: https://jsfiddle.net/wjdo23kr/