javascript - 从表单提交中提取 ID 的更好方法 Javascript/Django

标签 javascript jquery django forms post

目前我编写的代码可以工作,但看起来相当粗糙。基本上这就是我所拥有的(简化的):

JQuery 就绪:

<script type="text/javascript">

    $(document).ready(function() {
        $('div.partDelete').click(function() {

        // TODO this seems like a dirty hack
        var split = this.id.split('_');
        if(split.length == 3) {
            $('#part_id').val(split[0]);
            alert($('#part_id').val());
            $('#removePartForm').submit();
        } else {
            alert('There was a problem removing the selected part');
        }
    });

</script>

我正在使用的表格:

<form id="removePartForm" action="{% url remove_part %}" method="post">
    <input type="hidden" id="part_id" name="part_id" value="-1" />

    {% for part in current_build.parts.all %}
        <div id="{{ part.id }}_part_id" class="partDelete">remove</div>
    {% endfor %} 
</form>

我想做的就是设置隐藏输入以获取用户选择的part.id,以便我可以在我的 View 中使用它。

据我所知,这是解决此问题的正确方法,但我只是有一种感觉,事实并非如此。我是 Django 和 JQuery 的新手,因此可能有一些我还没有找到的内置功能。<​​/p>

感谢您提出的任何建议!

解决方案(请参阅下面 mikaelb 的回答)

Javascript:

$('div.partDelete').click(function() {
    var selected_id =$(this).data("id");
    $('#part_id').val(selected_id);
    $('#removePartForm').submit();
});

HTML 更改:

<div class="partDelete" data-id="{{ part.id }}">remove</div>

最佳答案

首先; ID 不应以数字开头 (http://www.w3.org/TR/html4/types.html#type-name)。

除此之外,您通常会使用 data-* 属性来设置 ID,以便从服务器端与 JS 进行通信。 data-* 属性可以是您想要的任何内容。所以 data-foo=""是一个有效的属性。

示例:
HTML:

<div class="item" data-id="{{ part.id }}">
    <p>Foo</p>
</div>

Javascript:

$(function () { // same as document read

    $(".button-class").on("click", function () {
        // Here "this" will be the element
        var id = $(this).data("id"); // same as getting attribute data-id
        // Could also use $(this).attr("data-id")
    });
});

希望这有帮助。

编辑:移动注释以使其更加清晰,更改示例以更具体地解决OP的问题。

关于javascript - 从表单提交中提取 ID 的更好方法 Javascript/Django,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643761/

相关文章:

javascript - Dojo:动态添加按钮

javascript - 使用 JavaScript 在特殊字符处拆分字符串

jquery - 单击 jQuery UI 对话框中的按钮之一

javascript - 使用 jQuery 捕获当前(不是之前)选择的单选按钮的值

python - Haystack Whoosh 没有索引所有内容

javascript - 带有两个提交按钮的 ASP.NET 表单不起作用

javascript - 我如何使用 Google Maps geocoder.getLatLng() 并将其结果存储在数据库中?

javascript - 如何通过id加载面板?

AJAX 轮询与 WebSockets 移动性能

python - Django Apache 2 ModuleNotFoundError : No module named 'django'