【问题标题】:Create an append by getting id通过获取 id 创建追加
【发布时间】:2018-12-20 04:14:04
【问题描述】:

所以我想拥有它,以便当我点击它时

<a class="tab" id="NAME">NAME</a>

在 id=gamecontent 中它会创建这个

<div id="NAME" class="tabcontent">
<h3>NAME</h3>
<embed src="games/NAME.swf" align="middle" height="570px" width="100%"/>
</div>

这就是我想出来的

$('.tab').click(function() {
var x = $(this).getAttribute('id');
$('#gamecontent').append('<div id="' + x + '" class="tabcontent"><h3>' + x + '</h3><embed src="games/' + x + '.swf" align="middle" height="480px" display="block" width="100%"/></div>');
});

它看起来很简单,但有些地方让它根本不起作用

【问题讨论】:

  • getAttribute 是一个普通的 js .. .attr() 是一个 jquery .. 所以你只需要将 .getAttribute('id') 更改为 attr('id')var x = this.id
  • 啊谢谢!我知道它必须是小东西

标签: jquery append getattribute


【解决方案1】:

正如评论所说,您使用了错误的方法来获取id 属性。更正了该错误,我展示了使用 JQuery 创建元素的替代方法,而不是使用完整的字符串定义:

$('.tab').click(function()
{
    var x = $(this).attr('id');
    
    var div = $("<div>", {
        id: x,
        class: "tabcontent"
    });

    var h3 = $("<h3>").text(x);
    
    var embed = $("<embed>", {
        src: "games/" + x + ".swf",
        align: "middle",
        height: "480px",
        width: "100%",
        display: "block"
    });

    div.append([h3,embed]);
    $("#gamecontent").append(div);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<a class="tab" id="NAME">NAME</a>
<hr>
<div id="gamecontent"></div>

点击后,您可以使用检查器工具检查附加内容的格式...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-12
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 2014-06-22
    • 2016-05-12
    • 2013-03-10
    相关资源
    最近更新 更多