【问题标题】:access multiple html data attributes with jQuery 'this'使用 jQuery 'this' 访问多个 html 数据属性
【发布时间】:2012-03-26 18:18:34
【问题描述】:

好的,标题可能有点混乱。让我解释一下。

<div class="book">
    <h3>Name of Book</h3>
    <p>
        <span data-notmobile="Author"></span>Rajesh K. Maurya</p>
    <p>
        <span data-notmobile="Publication"></span>Wiley India</p>
    <p>
        <span data-notmobile="Edition"></span>2011</p>
    <p>
        <span data-notmobile="Branch"></span>Information Technology</p>
    <p>
        <span data-notmobile="Semester"></span>5</p>
</div>

现在我想要一种方法将每个跨度的内容分别替换为其数据属性。 我试过了

$('.book span').html($('.book span').data("notmobile"));

这只会将内部 html 更改为第一个属性,即“作者”。出于某种原因,“this”关键字不起作用。

我想这样做而不给每个跨度一个自己的类。

【问题讨论】:

  • 附言。您的代码中的“this”在哪里?

标签: jquery this html


【解决方案1】:
$('.book span').each(function(){
    $(this).html($(this).data("notmobile"));
});

LIVE DEMO

【讨论】:

  • @supernoob。没问题。我添加了一个演示,希望你喜欢。
【解决方案2】:

$('.book span').data('notmobile') 返回第一个匹配元素的值。使用以下代码可以获得正确的预期效果:

演示:http://jsfiddle.net/Gezxj/

$('.book span').html(function() {
    return $(this).data("notmobile");
});

【讨论】:

  • This fiddle 很容易搞定。刚刚将 CSS 添加到您的小提琴中
【解决方案3】:
$('.book span').each(function() {
    var $this = $(this);
    $this.html($this.data('notmobile')); 
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2016-06-10
    • 1970-01-01
    相关资源
    最近更新 更多