javascript - 在js中访问动态id
问题描述
在 html 我有一个 div
<div class="row" id='textdrag{{$index}}'>
我需要使用 id 来显示基于 id 的上下文菜单,比如。
$("#textdrag2").contextmenu(function (event) {
setcontextposition("text");
});
但由于某种原因,没有显示上下文菜单。
当我只使用没有 $index 的 id="textdrag" 时,它的工作正常
解决方案
为什么它不能按目前的方法工作?
基本上,您的 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");
});
}
}
}])
推荐阅读
- html - AMP - 显示更多和更少的动态列表选项
- javascript - Javascript + PHP - 根据单选选项填充选择,但从数据库中获取结果
- c - C 中 *string 的 UpCase
- c - 两个静态变量的相同内存位置分配
- r - R中是否有执行独占完全连接的功能?
- android - android中的SearchView在列表中不显示任何内容
- google-pagespeed - Google 页面速度错误消息:Lighthouse 返回错误:FAILED_DOCUMENT_REQUE
- qt - 如何将 Qml 插件库导入另一个项目?
- python - 在一行中赋值、比较和使用值
- python - 为什么python将字节迭代为整数?