gpt4 book ai didi

javascript - Turbolinks:JavaScript 在 DOM 完全加载之前触发

转载 作者:行者123 更新时间:2023-12-02 21:03:30 25 4
gpt4 key购买 nike

我目前正在使用 JavaScript 开发 Rails 6 应用程序。我有一个文件 javascript/packs/posts.js ,它似乎在 DOM 完成加载之前触发。我尝试了以下方法,但没有成功。

document.addEventListener('readystatechange', event => {
if (event.target.readyState === "complete") {
} })

还添加了 document.addEventListener('turbolinks:load', event => {//code here })

但是,当我导航到出现错误的网站时,这不起作用。

TypeError: profileAvatarBlock is null

不知道会是什么。

document.addEventListener('turbolinks:load', event => {
// if (event.target.readyState === "complete") {
const fileUploadElement = document.getElementById('file-upload');
console.log(fileUploadElement)

if(fileUploadElement) {
fileUploadElement.addEventListener('change', function(){
const fileName = document.getElementById("post_image").files[0].name
const fileNameElement = document.getElementById('file-name');

fileNameElement.innerText = `${fileName}`
})
}

/**
* Display the image in the file input when added to the form.
* Replace avatar with image selected.
*/
let profileAvatarBlock = document.getElementById('profile-avatar');

function showImage(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();

reader.onload = function (e) {
let avatarPreview = document.getElementById('profile-avatar-preview');
let imageEl = avatarPreview.children[1]

imageEl.setAttribute("src", e.target.result);

['width', 'height'].forEach(attribute => {
imageEl.removeAttribute(attribute)
});

};

reader.readAsDataURL(input.files[0]);
}
}

profileAvatarBlock.addEventListener('change', function() {
showImage(this);
})
// }
});

尽管元素存在,为什么 let profileAvatarBlock = document.getElementById('profile-avatar'); 返回 null?

    <div class="rounded-full h-24 w-24 flex items-center justify-center upload-btn-wrapper" id="profile-avatar-preview">
<%= f.file_field :avatar, as: :file, id: "profile-avatar" %>
<%= cl_image_tag "#{ UsersHelper::AVATAR_ADD_ICON }", width: '50', height: '50', class: 'hover:bg-transparent' %>
</div>

以下行中的 console.log 也在 console.log(fileUploadElement) 行上返回 null

enter image description here

这种情况我能做什么?这是 JavaScript 问题还是 Turbolinks 问题?

最佳答案

如果无法与应用程序交互并查看该元素是否确实存在,则很难准确找出问题所在。不过,这里有一个尝试和调试此计时问题的好方法。尝试使用 MutationObserver ( https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver ) 并将目标节点作为 document

像下面这样的东西应该有助于调试这个

const m = new MutationObserver((mutations, obs) => {
for (const mut of mutations) {
if (mut.type === "childList" && mut.target.id === 'profile-avatar')
console.log(mut);
}
});

m.observe(document, { childList: true, subtree: true });

关于javascript - Turbolinks:JavaScript 在 DOM 完全加载之前触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61282603/

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