weex icon indicating copy to clipboard operation
weex copied to clipboard

使用repeat,在其中设置点击事件传递$index,log提示undefine

Open shangcongrong opened this issue 9 years ago • 6 comments

<div repeat="{{v in viewData}}" id="{{v.id}}"  onclick="clicked($index)">

  clicked: function(position) {
    console.log("被点到了:"+position)
  },

此时点击之后会提示undefine

如果div中设置成onclick="clicked({{$index}})"就会提示:

Uncaught TypeError: Cannot read property 'call' of undefined(…)

请问这种每个item想设置点击事件,并且将position作为参数传递进去该如何做?

shangcongrong avatar Dec 20 '16 12:12 shangcongrong

<div repeat="{{v in viewData}}" id="{{v.id}}" testid="{{v.id}}"  onclick="clicked">
var position = e.target.attr.testid

发现新增一个属性,通过target去取就可以了,不知道为什么不可以通过onclick传参数过去

shangcongrong avatar Dec 20 '16 13:12 shangcongrong

onclick 应该还需要在后面带上 $event 这个参数吧 @Hanks10100

acton393 avatar Dec 20 '16 13:12 acton393

@acton393 我试的不带也可以通过e.target.attr.testid去获取

shangcongrong avatar Dec 20 '16 13:12 shangcongrong

#1964 可以在这讨论一下

acton393 avatar Dec 21 '16 01:12 acton393

@shangcongrong 的方法是正确的,这样就可以取到repeat 中的值了 如 :

       <div class="num" repeat ="(index,val) in status">
          <a class="a" onclick="chooseNum($event)" aid="{{index}}">
              {{val.id}}</a>
       </div>

然后 通过 $event.target.attr.aid 就可以取到了,另外如果 在chooseNum ()中传值是 status 也是可以的,就是说 在chooseNum ()中传的值可以是 $event,可以是 data 中的值,也可是确定的值不是变量如 1,2 ,否则就是 undefined

Lx15 avatar Dec 21 '16 13:12 Lx15

我本地测试了一下,下边这个例子是可以正常工作的:

<template>
  <div>
  <div repeat="{{v in viewData}}" onclick="clicked($index)">
    <text>{{v}}</text>
  </div>
  </div>
</template>

<script>
  module.exports = {
    data: {
      viewData: ['a', 'b', 'c']
    },
    methods: {
      clicked: function(position) {
        console.log("被点到了:" + position)
      },
    }
  }
</script>

线上网站(http://dotwe.org/)中的 js framework 版本较低,马上会升级。

Hanks10100 avatar Dec 28 '16 11:12 Hanks10100