我的JSP有一个标签,其id正在动态填充:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
JS:
function GetAdvisorReview(){
var domElement =$(event.target);
console.log(domElement.attr('id'));
alert($(this).attr('id'));
alert(this.id);
alert(event.target.id);
}
每个提醒都是未定义的。请告诉我代码有什么问题。谢谢提前!!!!
答案 0 :(得分:3)
尝试在this
onclick()
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
Js应该是:
function GetAdvisorReview(e){
alert(e.id); //Get the Id
}
e
是触发事件的元素。
答案 1 :(得分:0)
如果你想拥有sender元素和事件对象,你应该这样做:
<a id="${advisor.getAdvisorId()}" href="#" onclick="GetAdvisorReview(this, event)" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
然后你可以这样访问它们:
function GetAdvisorReview(sender, e){
alert(sender.id);
alert(e.target.id);
}
答案 2 :(得分:0)
Wilfredo P是一个很好的方法,但我建议通过在所有链接中添加CSS类并使用addEventListener()
(纯JS)或.on()
(jQuery)来避免使用内联JS绑定click事件:
c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" class="someClass" href="#" onclick="GetAdvisorReview()" data-toggle="modal" data-target="#datepay">img src="assets/img/services/Icon_Reviews.png" width="50" alt="">/a>
</c:forEach>
var elems = document.getElementsByClassName("someClass");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("click", function() {
alert( elems[0].getAttribute("id") );
});
}
// jQuery
$(document).ready(function() {
$(".someClass", this).on("click", function() {
alert( $(this).attr("id") );
});
});
// Pure JS
var elems = document.getElementsByClassName("someClass-js");
for ( i=0; i<elems.length; i++ ) {
elems[0].addEventListener("mouseup", function() {
alert( this.getAttribute("id") );
});
}
// jQuery
$(document).ready(function() {
$(".someClass-jquery", this).on("click", function() {
alert( $(this).attr("id") );
});
});
a {
display: block;
}
p {
margin-bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>With Pure JS:</p>
<a id="some-link-1" class="someClass-js" href="#">Some Link 1</a>
<a id="some-link-2" class="someClass-js" href="#">Some Link 2</a>
<p>With jQuery:</p>
<a id="some-link-3" class="someClass-jquery" href="#">Some Link 3</a>
<a id="some-link-4" class="someClass-jquery" href="#">Some Link 4</a>
答案 3 :(得分:0)
循环中有HTML标记错误。我假设那些都是 仅粘贴拼写错误。否则,请修复这些以及我的代码块显示。
事件监听器解决方案是我将采取的方法。
删除onclick,将其替换为类:
<c:forEach var="advisor" items="${advisors}">
<a id="${advisor.getAdvisorId()}" href="#" class="advisors" data-toggle="modal" data-target="#datepay">
<img src="assets/img/services/Icon_Reviews.png" width="50" alt="">
</a>
</c:forEach>
然后听取该类点击事件的发生
$(".advisors").click(function() {
alert($(this).attr('id'));
});