protectDefault работает один раз, а .on вообще не работает

0

Я пытаюсь обработать некоторые результаты, пытаясь эмулировать цикл for и останавливаться в каждом элементе, пока пользователь не решит, что с ним делать. Дело в том, что я пытаюсь использовать event.preventDefault, чтобы избежать отправки формы, с которой она работает в первый раз, однако если я попробую снова с другой кнопкой, она просто пропустит ее и отправит форму.

Я прочитал об использовании.on() [delegate is revrecated] и попробовал это, но я предполагаю, что я делаю что-то неправильно, потому что не работает даже в первый раз.

<script>
    $(function() {
        //alert('era');
        var items = {{partial_results|length}};
        var current_item = {{current_item}};
        alert("current_item " + current_item);
        alert("items " + items);
        var project = {{project.id}}

        for (var i = items; i > current_item; i--) {
            $('#partial-' + i).hide();
        }

        $("#add-button-" + current_item).hide();
        $('#create-button-' + current_item).hide();


        var site_id = 'none';
        $("input:radio:checked").data("chk", true);
        $("input:radio").click(function() {
            //     alert("radio " +current_item);
            $("input[name='site-" + current_item + "']:radio").not(this).removeData("chk");
            //$("input[name='site-" + current_item + "']:radio").not(this).prop('checked', false);
            //$(this).prop;
            $(this).data("chk", !$(this).data("chk"));
            $(this).prop("checked", $(this).data("chk"));
            if ($("input:radio[name='site-" + current_item + "']").is(":checked")) {
                site_id = $(this).val();
                //     alert('checked '+current_item);
                $("#add-button-" + current_item).show();
                $('#create-button-' + current_item).hide();
            } else {
                //    alert('unchk '+current_item);
                $('#create-button-' + current_item).show();
                $("#add-button-" + current_item).hide();
            }
        });
        $('#add-button-' + current_item).on("click", "input", function(event) {
            //  $('#add-button-' + current_item).click(function(event) {
            alert('add');
            event.preventDefault();
            // alert(site_id);
            var data = {
                current_it: current_item,
                site_id: site_id,
                project_id: project,
                site_info: $('#site-to-' + current_item).serializeArray()
            };
            $.ajax({
                type: 'post',
                url: '{{ path("project_associate_site") }}',
                data: data,
                success: function(data) {
                    alert('success');
                    alert("current_item response " + current_item++);
                    for (var i = items; i > current_item; i--) {
                        $('#partial-' + i).hide();
                        alert("i #partial-" + i + ".hide()");
                    }
                    for (var j = 1; j < current_item; j++) {
                        $('#partial-' + j).hide();
                        alert("J partial-" + j + "hide()");
                    }
                    $('#partial-' + current_item).show();
                    $("#add-button-" + current_item).hide();
                    $('#create-button-' + current_item).hide();
                    alert("current_item response end" + current_item);
                    if (current_item > items) {
                        alert('>>');
                        window.location.href = "{{ path('project_show', { 'id': project }) }}";
                    }
                }
            });
        });
        $('#create-button-' + current_item).on("click", "input", function(event) {
            // $('#create-button-' + current_item).click(function(event) {
            alert('#create-button-' + current_item);
            event.preventDefault();
            alert('prevented');
            var data = {
                current_it: current_item,
                site_info: $('#site-to-' + current_item).serializeArray()
            };
            $.ajax({
                type: 'post',
                url: '{{ path("site_create_processing") }}',
                data: data,
                success: function(data) {
                    alert('success');
                    alert("current_item response " + current_item++);
                    for (var i = items; i > current_item; i--) {
                        $('#partial-' + i).hide();
                        alert("i #partial-" + i + ".hide()");
                    }
                    for (var j = 1; j < current_item; j++) {
                        $('#partial-' + j).hide();
                        alert("J partial-" + j + "hide()");
                    }
                    $('#partial-' + current_item).show();
                    $("#add-button-" + current_item).hide();
                    $('#create-button-' + current_item).hide();
                    alert("current_item response end" + current_item);
                    if (current_item > items) {
                        alert('>>');
                        window.location.href = "{{ path('project_show', { 'id': project }) }}";
                    }
                }
            });
        });
    });
    </script>
    <div id="content">
        <div class="page-full-width cf">
            <div class="content-module">
                <div class="content-module-heading cf">
                    <ul class="temporary-button-showcase">
                        <li><a href="{{ path ('project') }}" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
                    </ul>
                </div>
                <div class="content-module-main">
                    {% if error == 1 %}
                           {# <div class="error-box" align="center"> {{error_message}} </div> #}
                        <div align="center">
                            <br>
                            <br>
                            <h2>{{error_message}}</h2>
                        </div>
                    {% else %}
                           {% if partial_results|length %}
                            {% set i = 0 %}
                           {% for p_result in partial_results %}
                            <div id="partial-{{loop.index}}">
                                {% set i = i + 1  %}                     {# site #}
                                        <h1>Partial Matches:</h1>
                                        <form action="#pmatch" method="POST" {{ form_enctype(form) }}>

                                                        <div align="center">
                                                            <input type="submit" value="Add Site to Project" class="round blue ic-add" id="add-button-{{i}}">
                                                            <input type="submit" value="Create new Site" class="round blue ic-right-arrow" id="create-button-{{i}}">
                                                        </div>
                                                    </form>
                                                </div>
                        {% endfor %}
                                {% endif %}
                                                </div>
                                   {% endif %}
                                            </div>
                                        </div>
                                    </div>
{% endblock %}

Пожалуйста, игнорируйте синтаксис "странный", когда я использую Twig для управления шаблонами. Идея заключается в том, что в зависимости от пользователя, если он нажимает на создание нового или добавляет в проект, он должен выполнить этот бит кода, а затем вернуться и показать следующий результат. Он работает хорошо индивидуально, когда вы нажимаете либо, проблема возникает, когда он показывает вам следующий элемент, и вы пытаетесь сделать то же самое.

Заранее спасибо.

PD: вы можете видеть как.click, так и.on (один из них прокомментирован в каждом)

  • 5
    Это много кода. В любом случае, чтобы сузить это здесь?
  • 0
    уменьшенный код, просто оставив необходимый ...
Теги:
twig
preventdefault

2 ответа

1
Лучший ответ

Если $('#create-button-' + current_item) доступно в состоянии готовности:

$('#create-button-' + current_item).on("click", function(event) {
  //TODO
}

Должно работать.

Если $('#create-button-' + current_item) недоступно в состоянии готовности, попробуйте:

$(document).on("click", '#create-button-' + current_item, function(event) {
  //TODO
}

Другое решение может заключаться в том, чтобы дать все те же вещи, которые вы можете связать click по class и сделать что-то вроде:

$('.className').on("click", function(event) {
  //TODO
}

или

$(document).on("click", '.className', function(event) {
  //TODO
}

ОБНОВИТЬ:

Ваш JS привязывает только current_item. Итак, если ваш current_item равен 0 только #create-button-0 будет привязана к click. Я добавил, что, по-моему, может помочь с вашими кнопками. Дай мне знать, если это где-нибудь.

JS для кнопок:

$('.btn-add').on("click", function(e) {
   e.preventDefault();
   var index = $(this).parent().find('.selection-value').val();
   alert('add');

   var data = {
     current_it: index,
     site_id: site_id,
     project_id: project,
     site_info: $('#site-to-' + index).serializeArray()
   };

   $.ajax({
     type: 'post',
     url: '{{ path("project_associate_site") }}',
     data: data,
     success: function(data) {
       alert('success');
       alert("index response " + index++);
       for (var i = items; i > index; i--) {
         $('#partial-' + i).hide();
         alert("i #partial-" + i + ".hide()");
       }

       for (var j = 1; j < index; j++) {
         $('#partial-' + j).hide();
         alert("J partial-" + j + "hide()");
       }

       $('#partial-' + index).show();
       $("#add-button-" + index).hide();
       $('#create-button-' + index).hide();

       alert("index response end" + index);

       if (index > items) {
         alert('>>');
         window.location.href = "{{ path('project_show', { 'id': project }) }}";
       }
     }
   });
 });

 $('.btn-create').on("click", function(e) {
   event.preventDefault();
   var index = $(this).parent().find('.selection-value').val();
   alert('create');
   var data = {
     current_it: index,
     site_info: $('#site-to-' + index).serializeArray()
   };

   $.ajax({
     type: 'post',
     url: '{{ path("site_create_processing") }}',
     data: data,
     success: function(data) {
       alert('success');
       alert("index response " + index++);
       for (var i = items; i > index; i--) {
         $('#partial-' + i).hide();
         alert("i #partial-" + i + ".hide()");
       }

       for (var j = 1; j < index; j++) {
         $('#partial-' + j).hide();
         alert("J partial-" + j + "hide()");
       }

       $('#partial-' + index).show();
       $("#add-button-" + index).hide();
       $('#create-button-' + index).hide();

       alert("index response end" + index);
       if (index > items) {
         alert('>>');
         window.location.href = "{{ path('project_show', { 'id': project }) }}";
       }
     }
   });
 });

HTML PARSED:

<div id="content">
<div class="page-full-width cf">
    <div class="content-module">
        <div class="content-module-heading cf">
            <ul class="temporary-button-showcase">
                <li><a href="#" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
            </ul>
        </div>
        <div class="content-module-main">
            <div id="partial-0">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="0" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-1">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="1" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-2">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="2" />
                        </div>
                    </form>
                </div>
            </div>
            <div id="partial-3">
                <h1>Partial Matches:</h1>
                    <form action="#pmatch" method="POST">
                        <div align="center">
                            <input type="submit" class="btn-add round blue ic-add" value="Add Site to Project">
                            <input type="submit" class="btn-create round blue ic-right-arrow" value="Create new Site">
                            <input type="hidden" class="selection-value" value="3" />
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

HTML-БЛОК

<div id="content">
    <div class="page-full-width cf">
        <div class="content-module">
            <div class="content-module-heading cf">
                <ul class="temporary-button-showcase">
                    <li><a href="{{ path ('project') }}" class="button round blue image-right ic-left-arrow text-upper">Back</a></li>
                </ul>
            </div>
            <div class="content-module-main">
                {% if error == 1 %}
                       {# <div class="error-box" align="center"> {{error_message}} </div> #}
                    <div align="center">
                        <br>
                        <br>
                        <h2>{{error_message}}</h2>
                    </div>
                {% else %}
                       {% if partial_results|length %}
                        {% set i = 0 %}
                       {% for p_result in partial_results %}
                        <div id="partial-{{loop.index}}">
                            {% set i = i + 1  %}                     {# site #}
                                    <h1>Partial Matches:</h1>
                                    <form action="#pmatch" method="POST" {{ form_enctype(form) }}>

                                                    <div align="center">
                                                        <input type="submit" value="Add Site to Project" class="btn-add round blue ic-add">
                                                        <input type="submit" value="Create new Site" class="btn-create round blue ic-right-arrow">
                                                        <input type="hidden" class="selection-value" value="{{i}}" />
                                                    </div>
                                                </form>
                                            </div>
                    {% endfor %}
                            {% endif %}
                                            </div>
                               {% endif %}
                                        </div>
                                    </div>
                                </div>
{% endblock %}
  • 0
    то же самое, работает только один раз
  • 0
    @Splendonia Я добавил больше кода, чтобы посмотреть на мой пример.
Показать ещё 2 комментария
0

Есть ли какой-либо элемент ввода в любой из ваших кнопок? Удалить тег ввода может решить вашу проблему.

Например:

$('#add-button-' + current_item).on("click", function(event){ ...

Проверьте это, jquery doc on.on.

Здесь также прилагается jsfiddle, чтобы вы могли проверить, где вы поступили иначе.

JSFiddle нажмите здесь.....

  • 0
    Я думал, что <input type = "submit"> считается входным
  • 0
    @Splendonia Они считаются input данными, но вы уже начинаете с input когда используете $('#add-button-' + current_item)
Показать ещё 3 комментария

Ещё вопросы

Сообщество Overcoder
Наверх
Меню