我有一个关于获取每个元素的id的问题。 我有一个listview,当我点击每个元素时,我想得到最后一行的id('myID')。 我的问题是,每次点击都会得到相同的ID(39)
这是我的angularJS代码:
var app = angular.module('app', []);
function ctrlGenel($scope) {
$scope.call = function(){
var getID = angular.element(document.querySelector('#myID'));
alert(getID.html());
}
};
我的html如下所示:
<div ng-app='app' ng-controller='ctrlGenel'>
<div id='listview' ng-click='call()' class='listview'>
<h3>Title 1</h3>
<h4>Açıklama 1</h4>
<p id='myID'>39</p>
</div>
<div id='listview' ng-click='call()' class='listview'>
<h3>Title 2</h3>
<h4>Açıklama 1</h4>
<p id='myID'>40</p>
</div>
<div id='listview' ng-click='call()' class='listview'>
<h3>Title 3</h3>
<h4>Açıklama 1</h4>
<p id='myID'>41</p>
</div>
</div>
这是一个JSFiddle演示:http://jsfiddle.net/aldimeola1122/40rx6xwt/
你能帮帮我吗? 提前致谢。答案 0 :(得分:2)
试试这个:
您可以使用$ event of ng-click访问您单击的dom元素。 你只需要像控制器中的$ event.currentTarget一样调用currentTarget。
var app = angular.module('app', []);
function ctrlGenel($scope) {
$scope.call = function(event){
var getID = angular.element(event.currentTarget.querySelector('.myClass'));
alert(getID.html());
}
};
然后在你的html:
<div ng-app='app' ng-controller='ctrlGenel'>
<div id='listview' ng-click='call($event)' class='listview'>
<h3>Title 1</h3>
<h4>Açıklama 1</h4>
<p class='myClass'>39</p>
</div>
<div id='listview' ng-click='call($event)' class='listview'>
<h3>Title 2</h3>
<h4>Açıklama 1</h4>
<p class='myClass'>40</p>
</div>
<div id='listview' ng-click='call($event)' class='listview'>
<h3>Title 3</h3>
<h4>Açıklama 1</h4>
<p class='myClass'>41</p>
</div>
</div>
请注意,我使用的是class而不是id
答案 1 :(得分:1)
您可以尝试这样做:
<div ng-app='app' ng-controller='ctrlGenel'>
<div id='listview' ng-click="call('myID')" class='listview'>
<h3>Title 1</h3>
<h4>Açıklama 1</h4>
<p id='myID'>39</p>
</div>
<div id='listview' ng-click="call('myID1')" class='listview'>
<h3>Title 2</h3>
<h4>Açıklama 1</h4>
<p id='myID1'>40</p>
</div>
<div id='listview' ng-click="call('myID2')" class='listview'>
<h3>Title 3</h3>
<h4>Açıklama 1</h4>
<p id='myID2'>41</p>
</div>
</div>
和你的角色部分
var app = angular.module('app', []);
function ctrlGenel($scope) {
$scope.call = function(id){
var getID = angular.element(document.querySelector('#'+id));
alert(getID.html());
}
};