我有不同的“数据-id”属性的工具提示链接。
<a href="" class id="tooltip" data-id="125">Link</a>
<a href="" class id="tooltip" data-id="38">Link 2</a>
在这些情况下,"data-id“属性中的"125”或"38“应该与ajax一起发送到服务器端脚本,这取决于我悬停在哪个链接上。
问题是,当我悬停在链接1上时,只有第一个链接的“数据-id”属性才会被选中。当我在链接2上悬停时,我无法让我的脚本运行第二个链接的数据-id属性。而且控制台中没有显示错误。
jQuery(function($) {
var html_data = $("#tooltip").attr("data-id");
$( "#tooltip" ).tooltip({
content: function( response ) {
$.ajax({
url: "/datenbank/itemscript.php",
data: {
'var': html_data
},
type: "GET"
})
.then(function( data ) {
response( data );
});
},
items: "*"
});
});
发布于 2021-01-04 08:41:48
首先,您正在使用使用jQuery的id选择器。jQuery id选择器只选择一个元素,不再选择。因此,您的工具提示只应用于第一个链接。
要正确,您应该添加新的属性,如工具提示链接和删除重复的id=“工具提示”在2个链接,这是错误的。
<a tooltip-link data-id="124">Link</a>
<a tooltip-link data-id="83">Link 2</a>
在Javascript里
jQuery(function($) {
$( "[tooltip-link]" ).each(function(i) {
var id = $(this).attr("data-id");
$(this).tooltip({
content: function( response ) {
$.ajax({
url: "/datenbank/itemscript.php",
data: {
'var': id
},
type: "GET"
})
.then(function( data ) {
response( data );
});
},
items: "*"
});
})
});
如果您不喜欢修改html,可以执行以下操作
jQuery(function($) {
$( "[id='tooltip']" ).each(function(i) {
var id = $(this).attr("data-id");
$(this).tooltip({
content: function( response ) {
$.ajax({
url: "/datenbank/itemscript.php",
data: {
'var': id
},
type: "GET"
})
.then(function( data ) {
response( data );
});
},
items: "*"
});
})
});
发布于 2021-01-04 08:35:36
我认为您应该采取另一种方法来解决这类问题,因为如果您使用元素的id属性,它将从顶部第一次出现。
也许您可以尝试使用.mouseenter()函数,使用类属性,而不是id。
HTML:
<a href="" class="tooltip" data-id="125">Link</a>
<a href="" class="tooltip" data-id="38">Link 2</a>
jQuery:
$(document).on("mouseenter", ".tooltip", function(e){
var html_data = $(this).data('id');
$.ajax(...)
});
发布于 2021-01-04 08:41:05
它只获得第一个数据的原因是因为不能设置元素的相同id。以获取每个链接的数据id。而不是ID,使用工具提示作为类
像这样
<a href="" class="tooltip" data-id="125">Link</a>
<a href="" class="tooltip" data-id="38">Link 2</a>
JQuery
$( ".tooltip" ).tooltip({
let html_data = $(this).attr("data-id");
content: function( response ) {
$.ajax({
url: "/datenbank/itemscript.php",
data: {
'var': html_data
},
type: "GET"
})
.then(function( data ) {
response( data );
});
},
items: "*"
});
});
参见这里关于如何获取每个数据id的示例:
https://stackoverflow.com/questions/65565958
复制相似问题