Prototype.js在添加jQuery.replacement()后停止工作,其他jQuery工作正常



我正在为一个项目使用Acuity Scheduling。它使用prototype.js,并允许我将自己的自定义代码添加到页面的页眉和页脚(通过iframe提供给我的网站)。我不熟悉prototype.js,所以我使用jQuery的方式不会发生冲突。我的jQuery代码和prototype.js运行得很好,直到我添加了以下代码:

jQuery('body').html(jQuery('body').html().replace('an Appointment','a Session'));

我正在寻找一种方法,在不破坏其他jQuery代码或prototype.js的情况下,使用jQuery替换iframe中的特定单词。

你可以在这里看到我iframe的内容:https://acuityscheduling.com/schedule.php?owner=11134756

如果你查看源代码,你会看到我在底部添加的代码:

<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> 
<script language="javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery('body').on('click', '.time-selection', function() {
jQuery('.continueAlert').hide();   
jQuery('#rest').append('<p class="continueAlert">Please enter your name and contact info below.</p>');  
});
jQuery('body').html(jQuery('body').html().replace('an Appointment','a Session'));
});
</script>

谢谢你能提供的任何帮助!

我看到您已经通过原型针对特定元素设置了一些事件侦听器:

Event.observe(input, 'focus', function(){InputPrompt.focus(input);});
Event.observe(input, 'blur', function(){InputPrompt.blur(input);});
Event.observe(input, 'keypress', function(){input.label.hide();});

(可能还有更多,但这些是我能够迅速发现的)

当您替换元素的innerHTML属性(这就是您使用jQuery查找/替换片段所做的)时,浏览器基本上会"丢弃"旧的DOM元素并创建新的DOM元素。因此,更新innerHTML后,您在页面上看到的元素与之前看到的元素不同,这些元素都附加了事件侦听器。这就是为什么所有东西都"停止工作">

我看到两个选项:

  1. 更新查找/替换脚本以仅更新文本节点。这将确保具有事件侦听器的包含元素不会受到干扰。

  2. 使用不针对特定元素的事件委派。查看Event.on,密切注意可选的"selector"参数。类似于:

    document.on('cus','input',function(event,inputElement){InputPrompt.focus(inputElement);});

我觉得第一个选项对本页上已经建立的代码的干扰较小。

编辑:这里有一个非常暴力的方法来查找/替换所有文本节点(使用Prototype)。也许有一种更有效的方法可以做到这一点。不幸的是,你不能使用CSS选择器来匹配文本节点,因此所有的childNodes和whatnot-的过滤

document.body.select('*:not(script)').each(function(el){
$A(el.childNodes).each(function(child){
if (child.nodeType === 3) { // only get text nodes
child.nodeValue = child.nodeValue.replace('an Appointment', 'a Session');
}
})
});

相关内容

最新更新