【问题标题】:dynamically changing a div ID and other element's ID within the div动态更改 div 中的 div ID 和其他元素的 ID
【发布时间】:2015-08-23 22:06:51
【问题描述】:

这是我试图复制的 div

{%for i in current_user.posts%}
<div class = "own_posts" id = "{{'id_' + i.id|string}}">
    <img src = "{{url_for('static',filename='user_prof_pic/' + current_user.prof_pic)}}">
        <a href = "{{url_for('main.ProfilePage',user = current_user.first_name)}}">{{current_user.first_name}}</a>
    <p>{{i.post}}</p>
    <div class ="like_comment">
        <ul>
            <li><a href="#">like</a></li>
            <li><a href="#">comment</a></li>
        </ul>
    </div>
    <form class ="comment_form">
        <input type="text" action = "#" name = "comment_box" class ="comment_box" id = "{{'id_' +i.id|string}}">
        <input type="submit" value="comment" class ="submit" id = "{{'id_' + i.id|string}}">
    </form>
</div>
{%endfor%}

到目前为止,我已经成功地使用 jquery 预先添加它并更改新添加的 div 的 ID。

var count = 4

    $(".submit").click(function(event){
        event.preventDefault()

        var id = $(this).attr("id")
        var comment = $(".comment_box#" + id).val()
        console.log(count)
        count++
        $.ajax({
            type:"POST",
            url:"#",//"{{url_for('main.ProfilePage',user = current_user.first_name)}}",
            data: JSON.stringify({"comments":comment}),
            contentType:"application/json;charset=UTF-8"
        });

        var div_copy = $(".own_posts#id_2").clone()

        var div_copy2 = div_copy.attr("id","id_" + count)
        $("#own_stream").prepend(div_copy2)



    });

但是,前置 div 中的 ID 表单仍然包含克隆它的 div 的 ID。澄清 var div_copy = $(".own_posts#id_2").clone() 这个 div 中的表单包含 id_2 的 id,所以新添加的 div 的表单 id 仍然是 id_2

我更改了前置 div 的 ID 这样做:

var div_copy = $(".own_posts#id_2").clone()
var div_copy2 = div_copy.attr("id","id_" + count)
$("#own_stream").prepend(div_copy2)

但我不知道如何访问这个新克隆的 div 中的表单并将其更改为 ID

我们如何做到这一点?

我这样做对吗?我正在尝试学习 Web 开发,但不想了解 facebook、twitter 等网站如何在不刷新页面的情况下将您新发布的状态/推文显示到页面中。

我在做什么是如何工作的?如果不 对新手有所了解

这只是一个实践概念的测试

【问题讨论】:

  • ID 是开始学习如何使用 jQuery 的最简单的选择器......但对于这种情况,它们比使用普通类和遍历更复杂。例如,在您的每个 own-posts 容器中,一个简单的 find() 将隔离仅存在于该容器实例中的任何内容。
  • @charlietfl 你能写下一个例子作为答案让我接受吗?

标签: javascript jquery html python-3.x flask


【解决方案1】:

如果您只想使用 jQuery 检索表单元素,则根据您的来源,您有多种选择。

var form = $(".own_posts#id_2 > form");
/* or */
var form = $(".own_posts#id_2 > .comment_form");

我通常不建议使用直系后代方法,因为如果您的家谱将来发生变化,它将失败。您如此直观地使用模板,我认为未来可能对其进行更改。使用唯一标识符或已知单数类并搜索整个 div 链对我来说更有意义。

var form = $(".own_posts#id_2 .comment_form");
/* or */
var form = $(".own_posts#id_2").find(".comment_form");

这两个选项应该大致等同于您的目的,并且可以使用任何一个。

另外,我会小心使用非唯一 ID。您可以通过仅搜索较小的范围链来摆脱它,但您应该只在页面上有一个。这就是为什么大多数通过 id 检索的函数将只返回找到的第一个对象,而不是一个集合。

我不知道你是如何使用 id 的,但也许像 id="{{'posts_' + i.id|string}}" 之类的东西来利用唯一前缀。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2011-10-13
    • 2016-07-29
    相关资源
    最近更新 更多