[英]Tooltipster doesn't work with dynamically generated elements
我已經處理了幾天這個問題,但是找不到解決方案。 我有一個Javascript函數,在完成Ajax調用后會生成HTML,我這樣調用該函數:
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
});
接下來是我的功能:
function reloadInfo(id) {
var div = document.getElementById(id);
...
code += "<img id='led_" + res.id + "' src='green_led.gif' style='cursor: pointer' class='tooltipstered'>";
code += "<img id='" + res.id + "' src='mygraph.jpg'>";
...
div.innerHTML = code;
}
之后,我嘗試使用工具提示器,以便將鼠標放在“ green_led.gif”圖像上時將“ mygraph.jpg”顯示在工具提示中,並在移出鼠標光標時將其隱藏。 為此,我在$(document).ready()中使用了以下代碼:
$(document).ready(function() {
$("#list").change(function() {
reloadInfo($('#list').val());
});
reloadInfo($('#list').val());
$("body").on('mouseover', '.tooltipstered', function(){
$(this).tooltipster({
trigger: 'custom'
}).tooltipster('open').tooltipster('content', 'MYcontent');
});
});
但這似乎不起作用。 我已經閱讀了Tooltipster文檔,但是當我動態生成HTML代碼時(當我嘗試使用靜態HTML時,它可以工作,但是有點不同),我不知道我在做什么錯:
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
<body>
<button id="1" class="tooltipstered" style="float: right">Hover1</button>
<button id="2" class="tooltipstered">Hover1</button>
</body>
問題是當我使用JavaScript生成HTML時。 第一次將光標放在圖像上時,在瀏覽器控制台中沒有出現任何錯誤,但是第二次重復時,出現了以下錯誤:
<img id="led_27269" src="green_led.gif" style="cursor: pointer" class="tooltipstered">
如果有人知道我在做什么錯,那將是有幫助的。 非常感謝高級!!
兩件事情 :
tooltipster
並在HTML內容更改時重新創建它們。 tooltipster
方法應通過$(...).tooltipster(methodName, arg1, arg2,...)
。 在這里,您應該查看文檔以獲取正確的方法名稱和參數。 因此,您應該每次都在$("body").on('mouseover' ...
調用,而不用調用方法名稱。 休閑娛樂:
$(document).ready(function(){
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
})
});
應移動:
function reloadInfo(id) {
$(".tooltipstered").tooltipster('destroy');
... your reloading code
$(".tooltipstered").tooltipster({
trigger: 'custom',
arrow: false
}).on('mouseover', function() {
$(this).tooltipster('instance').content("foo").open();
}).on('mouseout', function() {
$(this).tooltipster('instance').close();
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.