小程序block进行for循环中input事件的处理?

<block wx:for="{{tips}}">
   <view style="width:100%;height:200rpx;">
      <input data-id="{{index}}" value="{{inputValue}}" bindfocus="bindFocus" bindinput="bindKeyInput" placeholder="输入文字以继续"/>
   </view>
</block>
 
  Page({
  data: {
    tips: [
      {
        id: 0
      },
      {
        id: 1
      }
    ],
    inputValue: '',
    focusId: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },

  bindFocus: function (event) {
    var id = event.currentTarget.dataset.id
    console.log(id)
    this.setData({
      focusId: id
    })
  },
  bindKeyInput: function (event) {
    var that = this;
    var value = event.detail.value
    var id = event.currentTarget.dataset.id
    console.log(that.data.focusId)
    this.setData({
      inputValue: value
    })
  }
    

clipboard.png

如上,小程序循环view后,绑定的input事件会同时响应,导致输入第一个input时,第二个input也是同样值(因为第一次事件已经赋值给inputValue了),有什么办法只在当前聚焦输入的input框显示当前输入值,其他input框不会跟随着显示,或者说,如何判断是哪个input框的点击事件?

已使用方法:
data-id={{index}}
js 中获取到event.currentTarget.dataset.id,但无法通过这个来判断

阅读 18.8k
1 个回答

居然你希望的是数据分开,那就将数据写入 tips 数组当中不就好了,例如:

<block wx:for="{{tips}}">
   <view style="width:100%;height:200rpx;">
      <input data-id="{{index}}" value="{{item.value}}" bindfocus="bindFocus" bindinput="bindKeyInput" placeholder="输入文字以继续"/>
   </view>
</block>
 
  Page({
  data: {
    tips: [
      {
        id: 0
      },
      {
        id: 1
      }
    ],
    inputValue: '',
    focusId: ''
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
  },

  bindFocus: function (event) {
    var id = event.currentTarget.dataset.id
    console.log(id)
    this.setData({
      focusId: id
    })
  },
  bindKeyInput: function (event) {
    var that = this;
    var value = event.detail.value
    var id = event.currentTarget.dataset.id
    var updateData = {
        inputValue: value
    };
    updateData['tips[' + id + '].value'] = value;
    console.log(that.data.focusId)
    this.setDataupdateData)
  }
    
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题