Gam*_*mer 6 javascript php jquery twitter-bootstrap tippyjs
我有以下代码,显示包含动态数据的工具提示.它的工作正常,但它显示了所有人的相同工具提示.
我用过的tip._tippy.destroy();位没用过.
<div id="template" style="display: none;">
Loading a tooltip...
</div>
Run Code Online (Sandbox Code Playgroud)
上面显示工具提示的元素:
<span class="more-tags otherPostTags" data-postId="{{$post->id}}">...</span>
Run Code Online (Sandbox Code Playgroud)
JS:
const template = document.querySelector('#template')
const initialText = template.textContent
const tip = tippy('.otherPostTags', {
animation: 'shift-toward',
arrow: true,
html: '#template',
onShow() {
const content = this.querySelector('.tippy-content')
if (tip.loading || content.innerHTML !== initialText) return
tip.loading = true
node = document.querySelectorAll('[data-tippy]');
let id = node[0].dataset.postid;
$.ajax({
url: '/get/post/'+id+'/tags',
type: 'GET',
success: function(res){
let preparedMarkup = '';
res.tags.map(function(item) {
preparedMarkup +=
'<span class="orange-tag" style="background-color: '+item.color+'">'+
item.name +
'</span>';
});
content.innerHTML = preparedMarkup;
tip.loading = false
},
});
},
onHidden() {
const content = this.querySelector('.tippy-content');
content.innerHTML = initialText;
},
});
Run Code Online (Sandbox Code Playgroud)
当我悬停时,tooptip显示来自数据库的标签,但它在悬停时显示相同的标签/数据,数据不同但显示首次悬停时出现的工具提示.
你的问题在这里:
node = document.querySelectorAll('[data-tippy]');
let id = node[0].dataset.postid;
Run Code Online (Sandbox Code Playgroud)
您始终选择相同的元素 ( node[0]) ,而不是选择当前悬停的元素。
您可以使用回调函数参数来获取单击的当前元素(onShow第一个参数包含对具有原始元素引用的对象的引用,在我的示例中 - tip.reference)。下面的例子:
node = document.querySelectorAll('[data-tippy]');
let id = node[0].dataset.postid;
Run Code Online (Sandbox Code Playgroud)
tippy.setDefaults({
arrow: true,
delay: 240,
theme: 'my-tippy',
onShow(tip) {
console.log('Post id: ' + $(tip.reference).data('postid'));
}
});Run Code Online (Sandbox Code Playgroud)
这是因为关键字const创建了一个只读变量。
常量是块作用域的,很像使用 let 语句定义的变量。
常量的值不能通过重新赋值而改变,也不能被重新声明。
您必须将其更改为varor let,因为它需要是mutable(但const不是)。
该
var语句声明一个变量,可以选择将其初始化为一个值。该
let语句声明一个块作用域局部变量,可以选择将其初始化为一个值。
抛开理论不谈,你必须更改const tip为var tip- 才能更新和/或销毁它。
根据以下标记 - 它仍然有点狭窄,因为它不是整个帖子标记的渲染 HTML 输出,因为需要以可靠的方式重现问题:
<span class="more-tags otherPostTags" data-postId="{{$post->id}}">...</span>
Run Code Online (Sandbox Code Playgroud)
人们可以(可能在事件源的范围内)获得类似的 id:
var id = parseInt($(this).data('postId'));
Run Code Online (Sandbox Code Playgroud)
处理 ids 的最常见方法是结合使用整个帖子节点的属性id(例如,使用类似 post_id 的属性)post_45
var id = parseInt($(selector).attr('id').replace('post_', ''));
Run Code Online (Sandbox Code Playgroud)
最重要的是,如果没有单个帖子的完整标记,我只能提示类似的语法$(this).parent().parent()...,这可能是获取句柄所必需的,需要相对于事件源进行选择。
| 归档时间: |
|
| 查看次数: |
1172 次 |
| 最近记录: |