[英]Find and Replace for whole page
我正在尝试为整个页面创建“查找并替换”。
我正在使用findandreplace这个迷你插件,它是:
function findAndReplace(searchText, replacement, searchNode) {
if (!searchText || typeof replacement === 'undefined') {
alert("Please Enter Some Text Into the Field");
return;
}
var regex = typeof searchText === 'string' ?
new RegExp(searchText, 'g') : searchText,
childNodes = (searchNode || document.body).childNodes,
cnLength = childNodes.length,
excludes = 'html,head,style,title,link,meta,script,object,iframe';
while (cnLength--) {
var currentNode = childNodes[cnLength];
if (currentNode.nodeType === 1 &&
(excludes + ',').indexOf(currentNode.nodeName.toLowerCase() + ',') === -1) {
arguments.callee(searchText, replacement, currentNode);
}
if (currentNode.nodeType !== 3 || !regex.test(currentNode.data) ) {
continue;
}
var parent = currentNode.parentNode,
frag = (function(){
var html = currentNode.data.replace(regex, replacement),
wrap = document.createElement('div'),
frag = document.createDocumentFragment();
wrap.innerHTML = html;
while (wrap.firstChild) {
frag.appendChild(wrap.firstChild);
}
return frag;
})();
parent.insertBefore(frag, currentNode);
parent.removeChild(currentNode);
}
}
目前,我需要使用find按钮为找到的每个Item制作一个单独的JS。 我做到了,所以为每个找到的项目添加了一个不同的随机ID。 现在我只需要JS。 当我完成整个操作后,我会想要它,因此,当您单击找到的单词之一时,它会弹出一个窗口(不发出警告),说:“将单词替换为:{INPUT HERE}”,然后它将仅替换该单词。 我认为那很酷。
我的查找代码是:
document.getElementById('find').onsubmit = function() {
findAndReplace(document.getElementById('fText').value, function(hi) {
var n = Math.floor(Math.random() * 9999999999);
var s = Math.floor(Math.random() * 30);
$('#fade').after('<span id="show' + n + '" style="display:none;"></span>');
$('#show' + n + '').html(hi);
$('body').prepend("<script type='text/javascript'>$('#highlight" + n + "').click(function(){$('#fade').show();});$('#highlight" + n + "').mouseover(function(){$('#highlight" + n + "').css('background', 'blue');});$('#highlight" + n + "').mouseout(function(){$('#highlight" + n + "').css('background', 'yellow');});</sc" + "ript>");
return '<span id="highlight' + n + '" style="background: yellow;color: black;">' + hi + '</span>';
});
return false;
};
我发现.html无法将<script>
标记放置到文档中,所以我希望有另一种方法可以做到这一点。 它看起来有点疯狂。 Mabye,您可以看得更清楚,知道我在这里想要什么
我希望有人能帮帮忙。 谢谢。
我在脚本末尾添加了以下代码。 它从提示中获取输入,但是它将“全部替换”,而不仅仅是单击的内容。
$('span[id^=highlight]').live('click', function () {
replacePrompt = prompt('Replace Word with:','{INPUT HERE}');
findAndReplace(document.getElementById('fText').value, function() {
return '<span class="highlight2" style="background: white;color: black;">' + replacePrompt + '</span>';
});
return false;
})
通过findAndReplace
函数后,也许我可以解决问题。
更新:一种解决方案是根本不使用findAndReplace
插件。 我仍然不确定,但这可能就是您想要的。
$('span[id^=highlight]').live('click', function () {
replacePrompt = prompt('Replace Word with:','{INPUT HERE}');
$(this).text(replacePrompt);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.