在下面的 html 中,我试图显示一个由 8 个单元格组成的表格 每个单元格显示一个图像,单击图像时它会调用changeImage函数,该函数获取图像id并更改图像。
//But its changing only one cell's image.When i click on image of any cell in table only first cell's image is changing.I know it is because of id="myImage" declared in img tag.I'm trying to generate Seperate Id for each image but unable to do so.
function changeImage() {
var image = document.getElementById('myImage');
if (image.src.match("bulbon")) {
image.src = "pic_bulboff.gif";
} else {
image.src = "pic_bulbon.gif";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div id="bottom">
<table id="t01" ng-if="Obj.Element">
<tr>
<th>hello</th>
<th ng-repeat=" ElementObj in Obj.Element"> {{ElementObj.a.b}}</th </tr>
<tr>
<div class="tooltip">
<th>{{Obj.c}}</th>
<span class="tooltiptext">{{Obj.d}}</span>
</div>
<th ng-repeat=" ElementObj in Obj.Element">
<div>
<img id="myImage" ng-click="changeImage()" src="pic_bulboff.gif" width="100" height="180">
</div>
</th>
</tr>
</table>
</div>
目标:当我单击表格的各个单元格时,它应该更改图像。我正在尝试显示一个由 8 个单元格组成的表格。每个单元格显示一个图像,单击图像时它会调用changeImage 函数,该函数获取图像 ID 并更改图像。
最佳答案
您不需要有 src
或 id
来处理更改图像,因为您已经有一个模型,并且可以更改模型而不是元素。
默认情况下,我们通过 ng-init
设置 src
,然后在 Controller 中更改它,如以下示例所示:
var app = angular.module("app", []);
app.controller("ctrl", function($scope) {
$scope.elements = [{
title: "A"
},
{
title: "B"
}
]
$scope.changeImage = function(element) {
var a = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQizZdER3przCQLcVB5b66j02wFyNRXxYIoYXIjqyntm2tpjIRA";
var b = "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png";
element.src = element.srcType ? a : b;
element.srcType = !element.srcType;
}
})
img {
width: 200px
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<div ng-app="app" ng-controller="ctrl">
<table class="table table-bordered">
<thead>
<th ng-repeat="element in elements"> {{element.title}}</th>
</thead>
<tbody>
<tr>
<td ng-repeat="element in elements">
<div ng-init="element.src = 'https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png';element.srcType=true">
<img ng-click="changeImage(element)" ng-src="{{element.src}}">
</div>
</td>
</tr>
</tbody>
</table>
</div>
关于javascript - 如何获取 ng-repeat 中生成的每个图像的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48901020/