【问题标题】:How to get value of custom data attribute in ionic?如何在离子中获取自定义数据属性的值?
【发布时间】:2022-01-20 20:57:32
【问题描述】:

我想在 ionic 中获取我的自定义数据属性的值。我尝试了很多方法,但没有一个对我有用。这是我的离子选择:

<ion-item>
  <ion-select value="اصفهان" (ionChange)="getCities($event)" [(ngModel)]="model.united" [ngModelOptions]="{standalone: true}" ok-text="تایید" cancel-text="کنسل">
    <ion-select-option value="{{item.name}}" data-id="{{item.id}}" *ngFor="let item of provinces">{{item.name}}</ion-select-option>
  </ion-select>
</ion-item>

我想在我的方法中获取 'data-id'。这是方法:

getCities($event) {
  const provinceId= $event.target.getAttribute('data-id');
}

但它返回 null。我该怎么办?

【问题讨论】:

    标签: angular ionic-framework


    【解决方案1】:

    您可以直接将item 作为值而不是item.name 传递并直接在您的函数中使用

    <ion-item>
      <ion-select value="اصفهان" (ionChange)="getCities($event)" [(ngModel)]="model.united" [ngModelOptions]="{standalone: true}" ok-text="تایید" cancel-text="کنسل">
        <ion-select-option [value]="item" data-id="{{item.id}}" *ngFor="let item of provinces">{{item.name}}</ion-select-option>
      </ion-select>
    </ion-item>
    

    组件函数

    getCities($event) {
      console.log($event, $event.id);
    }
    

    【讨论】:

    • 我试过了,但它返回“undefiend”
    • 未定义 $event$event.id ?
    • 对不起我的错误。我更改了“data-id”值,但您更改了值。现在它正在工作。谢谢
    【解决方案2】:

    target 属性没有getAtrributegetAtrribute 属性在$event 对象中可用。

    试试下面的代码

    getCities($event) {
      const provinceId= $event.getAttribute('data-id');
    }
    

    Example

    【讨论】:

    • 我试过这个但它有这个错误:“$event.getAttribute is not a function”
    • 将自定义数据保存在方括号内,如&lt;input type="hidden" class="test" value="0" [custom-data]="data.id" /&gt;
    猜你喜欢
    • 1970-01-01
    • 2021-08-25
    • 2013-04-16
    • 1970-01-01
    • 2015-09-28
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多