特定の名前を強調表示し、ツールチップ内の名前に関する追加情報を提供するクロム拡張機能をコーディングしようとしています。基本的に、次のような名前と ID を持つオブジェクトがあります。
var list = {
'Name1' : 'ID0001',
'Name2' : 'ID0002',
}
次に、jQuery ハイライト プラグインを使用して、ドキュメント内のすべてのキーの出現をハイライトし、キーの値に対応するクラス (例 ID0001) を持つスパン要素を割り当てます。これは正常に動作します...
$.each(list, function(key, value) {
$("p").highlight(key, {caseSensitive: false, className: value });
});
結果は次のようになります。
<span class="ID0001">Name_1</span>
次に、ID の最初の部分を含むクラス名を持つすべての要素を選択し、Tooltipster を有効にしようとしています。
$('span[class*=ID]').tooltipster({
interactive: true,
content: $(<p>Loading...</p>),
contentAsHTML: true,
functionBefore: function(origin, continueTooltip) {
continueTooltip();
// Below, I'm trying to get whole ID, without the
// 'tooltipstered' class, that Tooltipster assigned.
var id = $(this).attr('class').replace(' tooltipstered','');
$.getJSON(chrome.extension.getURL('db.json'), function(db) {
// Inside here, I'm using the ID to get information from a json
// file and store it in a variable called 'content', e.g.
var content = '<p>db[id].link</p>';
// Then I'm trying to update the content of the tooltip:
origin.tooltipster({
content: content,
contentAsHTML: true
});
}
});
このコードはすべて次の中にあります。
$(document).ready(function() { });
ここで、最初に名前が含まれるスパンにカーソルを合わせると、tooltipster は何も実行せず、Chrome コンソールには次のように表示されます。
Uncaught ReferenceError: content is not defined
しかし、もう一度カーソルを合わせると、正しいコンテンツが表示されます。さらに、最初に名前にカーソルを合わせ、2 回目に別の名前にカーソルを合わせると、最初の名前の内容がツールチップに表示されます。
私はJSとjQueryにかなり慣れていないので、ここで何が間違っているのかわかりません。
同様の問題に関する他のいくつかのスレッドを見つけましたが、提案された解決策はどれもうまくいきませんでした。
「完全な」更新コードは次のとおりです。
$(document).ready(function() {
$.each(list, function(key, value) {
$("p").highlight(key, {caseSensitive: false, className: value });
});
$('span[class*=ID]').tooltipster({
interactive: true,
contentAsHTML: true,
content: 'Loading...',
functionBefore: function(origin, continueTooltip) {
continueTooltip();
var id = $(this).attr('class').replace(' tooltipstered','');
var content = generate_content(id);
origin.tooltipster('content', content);
}
});
function generate_content(id) {
$.getJSON(chrome.extension.getURL('db.json'), function(db) {
// Getting information from the .sjon and storing it in "content"
});
return content;
}
});