开发者

Javascript - Get Meta Keywords and If Non Don't Break Bookmarklet

开发者 https://www.devze.com 2023-03-11 05:49 出处:网络
I have a bookmarklet that gets the meta keywords on a page. However if the there are no meta keywords the bookmarklet breaks.

I have a bookmarklet that gets the meta keywords on a page. However if the there are no meta keywords the bookmarklet breaks.

Here is my current javascript

function docoument_keywords(){
  var keywords;
  var metas = document.getElementsByTagN开发者_开发技巧ame('meta');

  for (var x=0,y=metas.length; x<y; x++) {
    if (metas[x].name.toLowerCase() == "keywords") {
      keywords = metas[x];
    }
  }

  return keywords.content;
}

k = document_keywords();

$('body').append("<p>" + k + "</p><p>Content</p>");

The bookmarklet works fine when there are actually keywords in the meta keywords. However its break when there are none. You guys have any solutions?

Much appreciated!


function document_keywords(){
    var keywords = '';
    var metas = document.getElementsByTagName('meta');
    if (metas) {
        for (var x=0,y=metas.length; x<y; x++) {
            if (metas[x].name.toLowerCase() == "keywords") {
                keywords += metas[x].content;
            }
        }
    }
    return keywords != '' ? keywords : false;
}

k = document_keywords();

if (k) {
    $('body').append("<p>"+k+"</p>");
}

Working example: JS Fiddle


Though Michael answered your question, I just wanted to point out that since you appear to already be using jQuery, this can be accomplished much, much more simply. Your script can be summarized thusly in its entirety:

$('body').append(
  "<p>" +
    $.map($('meta[name="keywords"]'), function(metaEl) { return metaEl.content; }) +
  "</p>"
);

// Or, on one line:

$('body').append("<p>" + $.map($('meta[name="keywords"]'), function(metaEl) { return metaEl.content; }) + "</p>");

Hope it's helpful!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号