这是Html代码:
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), :id => 'fav_id_002' %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites "), :id => 'fav_id_001' %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
以下是Javascript
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
//var value = $(this).val();
console.log(e.target.id);
//console.log(value);
});
//f1();
})
我无法获取点击链接的ID或值。如何获取被点击元素的ID?请帮助,谢谢。
答案 0 :(得分:0)
请参阅小提琴示例。这可能对你有帮助
$(document).ready(function(){
$(".test").click(function(){
var clickedId = this.id;
alert(this.id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="surya1" class="test">asda</a>
<a href="#" id="surya2" class="test">asd</a>
<a href="#" id="surya3" class="test">asdasd</a>
您所要做的就是为所有锚标签设置一个相同的类,然后按照下面的代码示例进行操作。
$(".linkClass").on("click", function() {
var clickedId = this.id;
}
答案 1 :(得分:0)
试试这段代码:
$('#fav_id').on('click', 'a', function(){
console.log($(this).attr('id'));
});
答案 2 :(得分:0)
这使它工作,不得不在html中改变一点。
<div class="ribbon-fav" id="fav_id">
<%- if user_signed_in? %>
<%- unless current_user.favorite_texts.exists?(id: text.id) -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite ", :id => 'fav_id_002') %>
<%- else -%>
<%= link_to image_tag("favd-hrt.png", size: "20x18", alt: "Remove from Favorites", title: " Remove from Favorites ", :id => 'fav_id_001') %>
<%- end -%>
<%- else -%>
<%= link_to image_tag("fav-hrt.png", size: "20x18", alt: "Add Favorite", title: " Add Favorite "), favorite_texts_path(text_id: text.id), method: :post, :'data-turbolinks-action' => 'replace' %>
<%- end -%>
</div>
从链接标记中删除id
并将其添加到img
标记。
和Javascript如下:
console.log("favorite_add_remove.js loaded");
$(document).ready(function(){
console.log("called function");
$("#fav_id a").on("click", function(e) {
e.preventDefault();
var imgIdVal = $('img', this).attr('id');
console.log(imgIdVal);
});
})
这使得输出为fav_id_002
;