简体   繁体   English

页面刷新-JavaScript

[英]Page refresh - JavaScript

I have a Rails application with JavaScript and it works when the document is loaded. 我有一个带有JavaScript的Rails应用程序,并且在加载文档时可以使用。 However, I need the JavaScript to reload when i go to a new page. 但是,当我进入新页面时,需要重新加载JavaScript。 Is there anyway to do this without reloading the page, or do i have to reload the page? 无论如何,有没有这样做而无需重新加载页面,还是我必须重新加载页面?

I've currently got the jQuery code written like this 我目前有这样写的jQuery代码

var main = function() {

var toggleProductImage = function() {
    $(this).children().each(function() {
        this.classList.toggle('hide');
    })
}

$('.ind a').each(function() {
    $(this).mouseenter(toggleProductImage);
    $(this).mouseleave(toggleProductImage);
}); 
}; 

Use delegated events with dynamically generated HTML, from eg. 将委托事件与动态生成的HTML结合使用,例如。 an ajax request. 一个ajax请求。 Find the closest parent that are static, I'm using document as I don't know your DOM tree: 找到最接近的静态父级,因为我不知道您的DOM树,所以我正在使用document

$(document).on('mouseenter', '.ind a', toggleProductImage)
           .on('mouseleave', '.ind a', toggleProductImage);

function toggleProductImage() {
    $(this).children().toggleClass('hide');
}

This will bind the events on document and only fire the handlers if a element matching .ind a the target. 这将把事件绑定到document并且仅当元素与.ind a匹配时才触发处理程序。

See more about .on( events [, selector ] [, data ], handler ) 进一步了解.on( events [, selector ] [, data ], handler )

events Type: PlainObject events类型:PlainObject
An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). 一个对象,其中的字符串键表示一个或多个用空格分隔的事件类型和可选的名称空间,并且值表示要为事件调用的处理函数。

selector Type: String selector类型:字符串
A selector string to filter the descendants of the selected elements that will call the handler. 一个选择器字符串,用于过滤将调用处理程序的所选元素的后代。 If the selector is null or omitted, the handler is always called when it reaches the selected element. 如果选择器为null或被省略,则处理程序在到达所选元素时始终被调用。

I also changed your toggleProductImage to make it more jQuery-like 我还更改了toggleProductImage ,使其更像jQuery

I don't think reloading the javascript is what you want. 我不认为您想要的是重新加载javascript。 You could get a js file and parse it again, however the objects from the previous load of the file will still be there. 您可以获取一个js文件并再次对其进行解析,但是文件先前加载的对象仍然存在。 You would have to keep track of everything you create, and remove all event handlers, then reload the js. 您必须跟踪创建的所有内容,并删除所有事件处理程序,然后重新加载js。

Instead I think you should attach the mouseenter / mouseleave on the parent element and filter the handler. 相反,我认为您应该将mouseenter / mouseleave附加在父元素上并过滤处理程序。

$('.ind').on('mouseenter', 'a', function(e) toggleProductImage);
$('.ind').on('mouseleave', 'a', function(e) toggleProductImage);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM