gpt4 book ai didi

javascript - 在 Rails 应用程序中运行 JavaScript

转载 作者:行者123 更新时间:2023-11-29 19:19:18 26 4
gpt4 key购买 nike

我正在学习 JavaScript 并尝试将其与 Ruby on Rails 结合使用。我有默认的 Rails 项目结构,我创建了一个简单的 assets/javascript/test.js 文件。

assets/javascript/test.js:

elements = document.getElementsByTagName('BODY');
console.log(elements[0]);

控制台的结果是未定义的,但是当我添加下一个代码时:

var elements = document.getElementsByTagName('*');
for (var i = 0; i < elements.length; i++) {
document.writeln(elements[i].tagName);
}

elements = document.getElementsByTagName('BODY');
console.log(elements[0]);

结果如预期 - body 标签。您能否解释一下发生了什么以及如何从 js 访问 body 标签及其元素?

使用:

console.log (document.body);

还在控制台中显示 null。

最佳答案

您需要将 JS 包装在 DOM 就绪事件中:

$(document).ready(function() {
//your code goes here
});

对于带有 Turbolinks 的 Rails:

.咖啡

ready = ->
//your coffeescript goes here

$(document).ready(ready)
$(document).on('page:load', ready)

.js

var ready = function() {
//your javascript goes here
};

$(document).ready(ready);
$(document).on('page:load', ready);

您的assets/javascript/test.js 文件:

var ready = function() {
console.log(document.body);
};

$(document).ready(ready);
$(document).on('page:load', ready);

解释:

来自 Using jQuery Core :

A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).load(function() { ... }) will run once the entire page (images or iframes), not just the DOM, is ready.

一旦在你的文档中遇到JS,它就会被执行。 Rails 通常通过加载在文档头部的 application.js 文件导入你的 JS。此时您的文档的其余部分甚至还没有加载,因此 JS 执行并找到部分未完成的 DOM - 主体尚未呈现。

要推迟执行您的 JS,您可以使用 $(document).ready 事件包装它 - 即注册它。您可以跨多个文件多次调用 $(document).ready。通常用它来包装你的文件是个好主意。

当整个文档加载完成后,所有 DOM 元素都加载完毕,jQuery 将触发 ready 事件并且所有在 $(document).ready 注册的代码都将获取执行。

涡轮链接

来自 Working with JavaScript in Rails # Turbolinks :

Turbolinks attaches a click handler to all <a> on the page. If your browser supports PushState, Turbolinks will make an Ajax request for the page, parse the response, and replace the entire of the page with the of the response. It will then use PushState to change the URL to the correct one, preserving refresh semantics and giving you pretty URLs.

When writing CoffeeScript, you'll often want to do some sort of processing upon page load. With jQuery, you'd write something like this:

$(document).ready ->
alert "page has loaded!"

However, because Turbolinks overrides the normal page loading process, the event that this relies on will not be fired. If you have code that looks like this, you must change your code to do this instead:

$(document).on "page:change", ->
alert "page has loaded!"

资源:

关于javascript - 在 Rails 应用程序中运行 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33701674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com