Created
January 8, 2016 07:17
-
-
Save yusukemurayama/29b85e14e9850fc0a8de to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
$.fn.disableOutboundLinks = function(config) { | |
var defaults = $.extend({ | |
ignoringDirs: "" // 無効化にしないディレクトリを「,」区切りで定義します。 | |
// 例)ignoringDirs: "foo, bar/baz" | |
}); | |
var options = $.extend(defaults, config); | |
/** | |
* カンマ区切りのディレクトリ名を、正規表現のパターンに変換します。 | |
* | |
* 例)foo, bar/baz -> /^(?:foo|bar\/baz)/ | |
*/ | |
function getHrefPattern(dirs) { | |
if (dirs.trim() === "") { | |
// ignoringDirsが指定されていない場合はnullを返します。 | |
return null; | |
} | |
var dirArray = dirs.split(",").map(function(dirname) { | |
dirname = dirname.trim(); // 空白を除去します。 | |
if (!dirname.endsWith("/")) { | |
dirname += "/"; // 末尾に「/」を追加します。 | |
} | |
dirname = dirname.replace(/([.\/])/g, "\\$1"); // 「.」や「/」をエスケープします。 | |
return dirname; | |
}); | |
return new RegExp("^(?:" + dirArray.join("|") + ")"); | |
} | |
// aタグ無効化を無視する、正規表現のパターンを取得します。 | |
var ptn = getHrefPattern(options.ignoringDirs); | |
return this.each(function(e) { | |
$(this).find("a").on("click", function() { | |
var $atag = $(this); | |
if (ptn === null) { | |
return false; // ignoringPattern指定なしの場合は、全て無効化します。 | |
} else if (!ptn.test($atag.attr("href"))) { | |
// パターンに一致しなかった場合、aタグを無効化します。 | |
return false; | |
} | |
}); | |
}); | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment