创建一个依赖于jQuery的Bookmarklet

时间:2014-01-21 01:29:03

标签: javascript jquery bookmarklet

我正在使用Coles先生的Bookmarklet创建者(http://mrcoles.com/bookmarklet/),但我似乎无法让这个javascript正常运行。这是我想在页面加载后运行的javascript。它应该弹出它在页面上找到的电子邮件和电话号码。如果jQuery包含在页面上,并且我将其粘贴到控制台中,那么它运行正常,但是从书签中它根据使用的生成器而有不同的错误。

helper = {};
helper.extractEmails = function (text) {
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}
email = "", phone = "";
if ($('a[href^="mailto"]').length > 0) {
    email = $('a[href^="mailto"]').attr("href").replace("mailto:", "").trim();
} else {
    email = helper.extractEmails($("body").html());
    if (email != null && email.length > 0) {
        email = email[0];
    }
}
if (email == null) {
    email = "";
}
phones = [];
str = $("body").text();
reg = /[0-9-()+]{10,20}/ig;
phoneNumber = /[0-9-()+]{10,20}/ig;
phones.push(str.match(phoneNumber)[0]);
if (phones.length > 0) {
    phone = phones[0];
}
alert("Email: " + email + "\r\nPhone: " + phone);

以下是确切的bookmartlet代码:

javascript:(function()%7Bfunction%20callback()%7B(function(%24)%7Bvar%20jQuery%3D%24%3Bhelper%20%3D%20%7B%7D%3Bhelper.extractEmails%20%3D%20function(%20text%20)%20%7Breturn%20text.match(%2F(%5Ba-zA-Z0-9._-%5D%2B%40%5Ba-zA-Z0-9._-%5D%2B%5C.%5Ba-zA-Z0-9._-%5D%2B)%2Fgi)%3B%7Demail%20%3D%20%22%22%2Cphone%20%3D%20%22%22%3Bif(%24('a%5Bhref%5E%3D%22mailto%22%5D').length%20%3E%200)%20%7Bemail%20%3D%20%24('a%5Bhref%5E%3D%22mailto%22%5D').attr(%22href%22).replace(%22mailto%3A%22%2C%20%22%22).trim()%3B%7D%20else%20%7Bemail%20%3D%20helper.extractEmails(%24(%22body%22).html())%3Bif(email%20!%3D%20null%20%26%26%20email.length%3E0)%20%7Bemail%20%3D%20email%5B0%5D%3B%7D%7Dif(email%20%3D%3D%20null)%20%7B%20email%20%3D%20%22%22%3B%7Dphones%20%3D%20%5B%5D%3Bstr%20%3D%20%24(%22body%22).text()%3Breg%20%3D%20%2F%5B0-9-()%2B%5D%7B10%2C20%7D%2Fig%3BphoneNumber%20%3D%20%2F%5B0-9-()%2B%5D%7B10%2C20%7D%2Fig%3Bphones.push(str.match(phoneNumber)%5B0%5D)%3Bif(phones.length%20%3E%200)%20%7Bphone%20%3D%20phones%5B0%5D%3B%7Dalert(%22Email%3A%20%22%2Bemail%2B%22%5Cr%5CnPhone%3A%20%22%2Bphone)%7D)(jQuery.noConflict(true))%7Dvar%20s%3Ddocument.createElement(%22script%22)%3Bs.src%3D%22https%3A%2F%2Fajax.googleapis.com%2Fajax%2Flibs%2Fjquery%2F1.7.1%2Fjquery.min.js%22%3Bif(s.addEventListener)%7Bs.addEventListener(%22load%22%2Ccallback%2Cfalse)%7Delse%20if(s.readyState)%7Bs.onreadystatechange%3Dcallback%7Ddocument.body.appendChild(s)%3B%7D)()

1 个答案:

答案 0 :(得分:1)

... A-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);}email = "",pho ...
                                       └─ You are missing a ";" at column 187.

实际上这不是生成器的错,因为你在代码中缺少分号:

helper.extractEmails = function (text) {
    return text.match(/([a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+)/gi);
}

现在,如果您将其添加回去,则可以:http://jsfiddle.net/3HrMB/2/


下次您可以使用JSLint查看问题所在:

enter image description here