首页 > 解决方案 > 在js中访问动态id

问题描述

在 html 我有一个 div

<div class="row"  id='textdrag{{$index}}'>

我需要使用 id 来显示基于 id 的上下文菜单,比如。

$("#textdrag2").contextmenu(function (event) {  
    setcontextposition("text");
});

但由于某种原因,没有显示上下文菜单。

当我只使用没有 $index 的 id="textdrag" 时,它的工作正常

标签: javascriptjqueryangularjs

解决方案


为什么它不能按目前的方法工作?

基本上,您的 javascript 会在加载后立即触发,但该实例textdrag{{$index}}尚未评估$index值。由于该事件尚未附加到该 DOM。


我宁愿建议您为此功能创建指令,这通常是在 AngularJS 中使用 DOM 的可行解决方案。通过这种方法,您无需为每个元素指定唯一标识符。

<div class="row" context-menu>
   ...
</div>

指示

app.directive('contextMenu', [function(){
   return {
      link: function(scope, element, attrs) {
         element.contextmenu(function (event) {  
            setcontextposition("text");
         });
      }
   }
}])

推荐阅读