此 jQuery 代码将在 wordpress 编辑器中作为书签运行。小书签/jQuery 代码将编辑内容字段中的文本并将参数(例如?参数)附加到 URL 的末尾。
URL 始终是相同的域名(例如 domain.com)。但是,URL 通常会包含目录(例如 domain.com/directory/index.html?parameter)。无论域名后面是什么,我都需要附加 jQuery 代码。
最复杂的情况是 domain.com/directory/index.html?someotherparameter?parameter
。此内容区域通常包含多个 url,因此脚本需要遍历整个文本。
我的半工作代码
var url= 'domain.com';
var append = ' ?parameter ';
$(".wp-editor-area").each(
function(){
var haystack = $(this).text();
$(this).text(haystack.replace(url, url+ append));
});
它正在修改的 HTML 代码
<div id="wp-content-editor-container" class="wp-editor-container"><textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content"><a title="This is a hyperlink" href="http://domain.com/directory">This is a hyperlink</a></textarea></div>
它的当前输出
<a title="This is a hyperlink" href="http://domain.com ?parameter /directory">This is a hyperlink</a>
请注意我的输出没有附加在整个 URL 之后。如果文本正文中有更多 URL,我如何针对更复杂的 URL 修改它并循环遍历文档?
我能找到的唯一相关且相似的问题是 this ,但是我无法复制结果。
谢谢!!
最佳答案
首先,the Fiddle .
您的示例代码完全按照您的要求执行。它将字符串的 'domain.com'
部分替换为域和您的参数。一旦找到 'domain.com'
,它就会停止查看是否还有其他附加内容。
尝试使用 a regular expression 而不是直接替换文本在字符串中查找 URL。
来源:
<div id="wp-content-editor-container" class="wp-editor-container">
<textarea class="wp-editor-area" rows="10" tabindex="1" cols="40" name="content" id="content">
<a title="This is a hyperlink" href="http://domain.com/directory">This is a hyperlink</a>
<a title="This is another hyperlink" href="http://google.com/directory">This is another hyperlink</a>
</textarea>
</div>
Javascript:
var url = 'domain.com';
var append = '?parameter ';
$(".wp-editor-area").each(function() {
$(this).text(urlify($(this).text()));
});
function urlify(text) {
var urlRegex = /(\b(https?|ftp|file):\/\/[domain.com][-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(urlRegex, function(url) {
return url + append;
})
}
关于javascript - jQuery 识别 URL 并追加参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11422274/