首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >StimulusJS目标未定义,但.querySelector工作

StimulusJS目标未定义,但.querySelector工作
EN

Stack Overflow用户
提问于 2022-11-22 08:35:02
回答 1查看 26关注 0票数 0

我很困惑。在刺激控制器中,我发现目标的行为不一致。

通过importmap pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true使用pin "@hotwired/stimulus", to: "stimulus.min.js", preload: true

我有一个基本形式的刺激控制器。

代码语言:javascript
复制
<%= form_with model: @message, data: { controller: "message-form" } do |form| %>

  <%= form.file_field :attachments, class: 'file-input', id: 'file-input', multiple: true, hidden: "hidden",
                      data: { message_form_target: "attachmentInput" } %>

  <i class="fa-solid fa-paperclip fa-lg" data-action="click->message-form#openAttachments"></i>


<% end %>
代码语言:javascript
复制
import {Controller} from "@hotwired/stimulus"

export default class extends Controller {
    static targets = ["messageInput", "sendBtn", "attachmentInput"]

    connect() {
        this.inputIsEmpty()
        console.log(this.attachmentInputTarget) // Outputs HTML element
    }

    openAttachments(){
        this.attachmentInputTarget.click()
        this.attachmentInputTarget.removeAttribute("hidden")
        setInterval(this.hideAttachments, 5000)
    }

    hideAttachments(){
        let attachmentInput = document.querySelector('#file-input')
        console.log(this.attachmentInputTarget) // Undefined
        console.log(attachmentInput) // Outputs HTML element
        console.log(document.getElementById('file-input') == this.attachmentInputTarget) // false

        if (!document.getElementById('file-input').files[0]) {
            attachmentInput.setAttribute("hidden", "hidden")
        } else {
            attachmentInput.removeAttribute("hidden")
        }
    }
}

因此,connect()中的attatchmentInputTarget按照我的预期操作,并输出hideAttachments元素,但是当hideAttachments被调用时,attatchmentInputTarget是未定义的。

EN

回答 1

Stack Overflow用户

发布于 2022-11-22 08:35:02

好吧,我把这一切都写出来了。

由于对setInterval的延迟调用,hideAttachments作为普通JS在刺激控制器外部被调用,因此没有对Target的引用。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74529613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档