jQuery Attr不输出

时间:2018-10-14 17:04:14

标签: jquery find

我正在尝试让jQuery的attr处理动态加载的内容。

$('.content').find('.game-release').html($(this).attr("data-timer"));

.content已加载到DOM中,.game-release已加载到AJAX动态内容中。

当我这样做时:

$('.content').find('.game-release').html("Hello");

div变为“ Hello”。在执行$(this).attr("data-timer")而不是“ Hello”时,它什么也没做。

div看起来像这样:

<div class="game-release" data-timer="10-08-2018 02:00:00">some text</div>

有人知道为什么会这样吗?

3 个答案:

答案 0 :(得分:1)

您要为HTML使用功能:

$('.content').find('.game-release').html(function() {
  return $(this).data("timer")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content">
  <div class="game-release" data-timer="10-08-2018 02:00:00">some text</div>
  <div class="game-release" data-timer="11-08-2018 02:00:00">some text</div>
  <div class="game-release" data-timer="12-08-2018 02:00:00">some text</div>
</div>

答案 1 :(得分:0)

致电时

services.AddScoped<IMiddleware, SomeMiddleware>();

$('.content').find('.game-release').html($(this).attr("data-timer")); 可能不是您认为的那样。通常是在/从中调用该函数的对象。

您可能会使用

对其进行修复
this

您可以尝试在调用var game_release = $('.game-release').first(); // Calling first because it's then more clear we're calling methods on only the first element in the collection, in case there are more .game-release elements. game_release.html(game_release.attr("data-timer")); 的内部发出console.log(this),以便在调用.html()函数时亲自了解this是什么。

答案 2 :(得分:0)

var time = $(".game-release").data('timer');
$('.game-release').html(time);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <div class="game-release" data-timer="10-08-2018 02:00:00">some text</div>