动态更改div中的div ID和其他元素的ID

时间:2015-08-23 22:06:52

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

这是我试图复制的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

我们如何实现这一目标?

我也是这样做的吗?我正在尝试学习网络开发,并且不想了解像facebook,twitter等网站如何在不刷新的情况下向页面显示您新发布的状态/推文。

我正在做的是如何运作的要点?如果不 揭示一个新手

这也只是练习概念的一个测试

1 个答案:

答案 0 :(得分: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}}"之类的东西来使用唯一的前缀。