ruby-on-rails 刺激控制器动作在点击时触发两次

ufj5ltwl  于 5个月前  发布在  Ruby
关注(0)|答案(1)|浏览(91)

出于某种原因,我的刺激控制器,加载一次,但行动是发射两次点击。
我找不到问题出在哪里...
我的代码很简单,所以我在下面分享一下:

// app/javascript/application.js
https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
// app/javascript/controllers/application.js
import { Application } from "@hotwired/stimulus"
const application = Application.start()
application.debug = false
window.Stimulus   = application
export { application }
// app/javascript/controllers/index.js
import { application } from "controllers/application"
import { eagerLoadControllersFrom } from "@hotwired/stimulus-loading"
eagerLoadControllersFrom("controllers", application)
// app/javascript/controllers/radio_button_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static classes = [ 'active', 'inactive', 'invisible' ]

  connect() {
    console.log('connected to ', this.element.querySelector('input').value)
  }

  markAsChecked(event) {
    event.stopPropagation();
    console.log('-', this.element.querySelector('input').value);
  }
}
// view.html.erb

<div class="flex flex-1 gap-x-8 justify-start">
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="public" name="destination[access_type]" id="destination_access_type_public">
  </label>
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="private" name="destination[access_type]" id="destination_access_type_private">
  </label>
  <label data-controller="radio-button" data-action="click->radio-button#markAsChecked:stop">
    <input type="radio" value="backend" name="destination[access_type]" id="destination_access_type_backend">
  </label>
</div>

当我在开发人员控制台中运行以下命令时,我也得到了双动作触发

// developer console
temp1 // label
temp1.click()
// - public
// - public
temp2 // input
temp2.click()
// - public


正如你所看到的,当我点击标签的时候,markAsynchronous被触发了两次,当我点击输入的时候,一次。我不知道为什么。
(我希望它总是触发一次)

af7jpaap

af7jpaap1#

这是默认的<label>元素行为:
当用户单击或触摸/轻敲标签时,浏览器将焦点传递到其关联的输入(也会为输入引发结果事件).

.单击以下代码片段中的label可以触发用户代理在input元素上激发click事件,就好像元素本身已经被用户触发一样:

<label><input type=checkbox name=lost> Lost</label>

字符串

  • 网址:http://html.spec.whatwg.org/multipage/forms.html#the-label-element*

请注意,当单击<label>时,您会得到两个事件,但event.target不同:

document.addEventListener("click", (event) => {
  console.log(event.target);
})
<label for="destination_access_type_public">click me</label>
<input type="radio" value="public" name="destination[access_type]" id="destination_access_type_public">

的数据
您可以将data-action添加到input以始终获得单个事件:

<label data-controller="radio-button">
  <input data-action="click->radio-button#markAsChecked" type="radio" value="public" name="destination[access_type]" id="destination_access_type_public">
</label>

相关问题