我一直想要并尝试创建一个“小”代码片段,在他们的头像上显示用户的名字。信息位于子域中,因此存在跨域问题。我把它整理好了,但是它有效,但是有一件事让我烦恼。
无论出于何种原因,我似乎无法将html元素中的值赋给变量。我也不能调用函数,所以我有重复的代码。
加载和执行代码段来自另一个SO问题,因为@require会终止整个脚本。
// ==UserScript==
// @grant GM_xmlhttpRequest
// ==/UserScript==
var load,execute,loadAndExecute;load=function(a,b,c){var d;d=document.createElement("script"),d.setAttribute("src",a),b!=null&&d.addEventListener("load",b),c!=null&&d.addEventListener("error",c),document.body.appendChild(d);return d},execute=function(a){var b,c;typeof a=="function"?b="("+a+")();":b=a,c=document.createElement("script"),c.textContent=b,document.body.appendChild(c);return c},loadAndExecute=function(a,b){return load(a,function(){return execute(b)})};
loadAndExecute("http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", function() {
var numNew = 0;
var numOld = 0;
if(localStorage) {
$(".user").each(function(i,v) {
var currentUser = $(this);
var profile = $(this).data("userprofile");
if(profile !== undefined) {
if(localStorage.getItem(profile)) {
numOld++;
currentUser.append('<span style="position: absolute;">' + localStorage.getItem(profile) + '</span>');
} else {
$.get('http://sub.domain.com/user/' + profile, function(data) {
numNew++;
currentUser.append('<span style="position: absolute;">' + $(data).find('.userNameContainer').text() + '</span>');
localStorage.setItem(profile, $(data).find('.userNameContainer').text());
});
}
} else {
var profile = $("img", this).data("miniprofile");
if(profile !== undefined) {
if(localStorage.getItem(profile)) {
numOld++;
currentUser.append('<span style="position: absolute;">' + localStorage.getItem(profile) + '</span>');
} else {
$.get('http://sub.steamcommunity.com/user/' + profile, function(data) {
numNew++;
currentUser.append('<span style="position: absolute;">' + $(data).find('.userNameContainer').text() + '</span>');
localStorage.setItem(profile, $(data).find('.userNameContainer').text());
});
}
}
}
});
console.log('Loaded from localStorage: ' + numOld);
console.log('Loaded from server: ' + numNew);
}
});
勘定
$(data).find('.userNameContainer').text()
变量什么都不做,甚至打破了脚本。为什么呢?
-
回应示例:
<div class="profile_content">
<div class="profile_top">
<div class="profile_user">
<div class="userAvatar">
<img src="">
</div>
<div class="user_content">
<div class="userid">
<span class="userid">1234</span>
</div>
<div><span class="userNameContainer">Mave</span></div>
</div>
</div>
</div>
</div>
</div>