如何在离子中获取自定义数据属性的值?

Posted

技术标签:

【中文标题】如何在离子中获取自定义数据属性的值?【英文标题】: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。我该怎么办?

【问题讨论】:

【参考方案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;

以上是关于如何在离子中获取自定义数据属性的值?的主要内容,如果未能解决你的问题,请参考以下文章