[英]jquery cannot get div to show using this selector
I am querying the Twitch API for a list of users in my database, to see if they are online. 我正在查询Twitch API以获取数据库中用户的列表,以查看他们是否在线。
I am essentially listing them all, with "display: none" and then unhiding if online: 我实质上是用“ display:none”列出所有内容,然后在线就隐藏起来:
$('.online_list').each(function (index) {
var tnick = $(this).data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a["streams"].length > 0)
{
alert(tnick);
$(this).show();
console.log(index + ": " + $( this ).text());
}
});
});
In my testing, the alert(tnick)
works perfectly, so I know it's running. 在我的测试中,
alert(tnick)
完美运行,所以我知道它正在运行。 The problem is $(this).show();
问题是
$(this).show();
just isn't working. 只是不工作。
Here's example HTML: 以下是HTML示例:
<div class="online_list" data-tnick="test" style="display: none;">test:<a href="https://www.twitch.tv/test">Twitch</a> <span>(Online)</span></div>
<div class="online_list" data-tnick="test2" style="display: none;">test2:<a href="https://www.twitch.tv/test2">Twitch</a> <span>(Online)</span></div>
this
is the current scope object! this
是当前作用域对象!
to fix your code you can do the following: 要修复您的代码,您可以执行以下操作:
$('.online_list').each(function (index) {
var $that = $(this); // create a temp var that
var tnick = $that.data('tnick');
$.getJSON("https://api.twitch.tv/kraken/streams?client_id={:twitch_key}&channel="+tnick+"", function(a) {
if (a && a["streams"] && a["streams"].length > 0) {
alert(tnick);
$that.show(); // use that instead of this
console.log(index + ": " + $that.text());
}
});
});
Check out this resource for more information on scope & this: http://javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/ 请查看此资源,以获取有关范围和此处的更多信息: http : //javascriptplayground.com/blog/2012/04/javascript-variable-scope-this/
EDIT: 编辑:
Also, like @djxak suggests, you can use the element
parameter of the callback, that is more simple and clean in my opinion. 另外,就像@djxak所建议的那样,您可以使用回调的
element
参数,在我看来,这更简单明了。
The @djxak suggests: @djxak建议:
$('.online_list').each(function (index, element) {
//... (scope1 code)
$.getJSON("", function(a) {
//... (scope2 code)
$(element).show();
});
});
My approach: 我的方法:
$('.online_list').each(function (index) {
//... (scope1 code)
var $current = $(this);
$.getJSON("", function(a) {
//... (scope2 code)
$current.show();
});
});
Info about each function and element
parameter in jQuery docs: https://api.jquery.com/each/#each-function 有关jQuery文档中每个函数和
element
参数的信息: https : //api.jquery.com/each/#each-function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.