Функция jQuery .click не работает должным образом

Я пытаюсь решить проблему с каким-то jQuery, который не работает должным образом. У меня есть эта функция щелчка, которая должна открывать либо модальное окно, либо текстовое поле, в зависимости от того, как оценивается инструкция if / else, но она не работает. Когда я загружаю страницу, ничего не происходит. Тем не менее, если я вставлю в код несколько операторов console.log, я могу увидеть, что «Click Apply» регистрируется, когда я нажимаю кнопку вместе с $(this).siblings(".apply-menu”), но текстовое поле не отображается.

Если я щелкну правой кнопкой мыши результат $(this).siblings(".apply-menu”) в консоли и сохраню его в переменной, а затем добавлю к нему .show(), поле появится, но затем сразу же исчезнет, ​​когда я щелкну по нему. Ошибок нет, и я изо всех сил пытаюсь понять, что здесь происходит. Также к кнопке не привязаны другие прослушиватели событий.

        $("button[menu='apply']").click(function(){
            console.log("Click Apply");
            if($('body').attr('signed-in') == "false"){
                console.log(true);
                $(this).siblings(".apply-menu").hide(); //hide dropdown for modal
                modal.open({
                    content: $('#signup_form').html(),
                    top: 130
                });
            } else {
                console.log($(this).siblings(".apply-menu"));
                $(this).siblings(".apply-menu").show();
            }
        });

Вот Еврорадио:

<div class="dropdown" id='dropdown{{j.id}}'>
    <% if user_signed_in? %>
    <button ng-if="checkIfAppliedToJob(j.id, appIDs) && $(statusIDs).filter([j.status_id]).size() > 0;" class="j-descrip-button thin" disabled>Pending</button>
    <button ng-if="!checkIfAppliedToJob(j.id, appIDs);" class="j-descrip-button thin job-dropdown-link" menu="apply">Apply</button>
    <% else %>
    <button class="j-descrip-button thin job-dropdown-link" menu="apply">Apply</button>
    <% end %>
    <div class="dropdown-menu middle apply-menu">
        <div class="dd_arrow_middle" style='z-index: -1;'></div>
        <div class="apply-dropdown-content">
            <% if user_signed_in? %>
            <% if !current_user.first_name.present? || !current_user.last_name.present? || !current_user.resume_file_name.present? %>
            <div>Oops! Looks like you need to provide us with some info - go to <%= link_to 'My Account', edit_user_registration_path %> to upload your resume and/or give us your name.</div>
            <% else %>
            <span class="apply-prompt"><%= @apply_question %></span>
            <br>
            <span class="outer-wc"><span class="word-count">0</span>/500 characters</span>
            <form accept-charset="UTF-8" action="{{'/applications?id=' + j.id}}" class="pitch-form" data-remote="true" html="{:role=>&quot;form&quot;}" id="{{j.id}}" method="post">
                <div style="margin:0;padding:0;display:inline">
                    <input name="utf8" type="hidden" value="✓">
                </div>
                <% if defined? @error_msg %>
                <span><%= @error_msg %></span>
                <% end %>
                <div class="form-group">
                    <textarea class="apply-textbox" id="pitch" name="pitch"></textarea>
                </div>
                <div style="display:none;"><input id="user_id" name="user_id" type="text" value="<%= current_user.id %>"></div> <!-- is this the best way to access the user, are there drawbacks? -->
                <div style="display:none;"><input id="job_description_id" name="job_description_id" type="text" value="{{j.id}}"></div>
                <div style="display:none;"><input id="company_id" name="company_id" type="text" value="<%= @company.id %>"></div>
                <input class="apply-submit-btn" name="commit" type="submit" value="Submit Application">
            </form>
            <% end %>
            <% else  %>
            <div>You have to sign in before you can apply to jobs.</div>
            <% end %>
        </div>
    </div>
</div>

Вот визуализированный HTML:

<div class="content">
    <div class="job-title ng-binding" style="background: #53AA2A">Lead Developer</div>
    <div class="job-role ng-binding" id="Ruby Ninja">Ruby Ninja</div>
    <p class="job-description ng-binding">Awesome sauce!</p>
    <div class="btn-holder">
        <div class="dropdown">
            <a href="http://www.google.com/" onclick="return !window.open(this.href,'', 'width=720,height=480,location=no,menubar=no,resizable=yes,scrollbars=yes,toolbar=no,status=no');"><button class="j-descrip-button thin">Read More</button></a>
        </div>
        <div class="dropdown" id="dropdown11">
            <!-- ngIf: checkIfAppliedToJob(j.id, appIDs) && $(statusIDs).filter([j.status_id]).size() > 0; -->
            <!-- ngIf: !checkIfAppliedToJob(j.id, appIDs); --><button ng-if="!checkIfAppliedToJob(j.id, appIDs);" class="j-descrip-button thin job-dropdown-link ng-scope" menu="apply">Apply</button><!-- end ngIf: !checkIfAppliedToJob(j.id, appIDs); -->
            <div class="dropdown-menu middle apply-menu">
                <div class="dd_arrow_middle" style="z-index: -1;"></div>
                <div class="apply-dropdown-content">
                    <span class="apply-prompt">What makes you and Ice 2 Go a good fit?</span>
                    <br>
                    <span class="outer-wc"><span class="word-count">0</span>/500 characters</span>
                    <form accept-charset="UTF-8" action="/applications?id=11" class="pitch-form ng-pristine ng-valid" data-remote="true" html="{:role=>&quot;form&quot;}" id="11" method="post">
                        <div style="margin:0;padding:0;display:inline">
                            <input name="utf8" type="hidden" value="✓">
                        </div>
                        <div class="form-group">
                            <textarea class="apply-textbox" id="pitch" name="pitch"></textarea>
                        </div>
                        <div style="display:none;"><input id="user_id" name="user_id" type="text" value="1"></div> <!-- is this the best way to access the user, are there drawbacks? -->
                        <div style="display:none;"><input id="job_description_id" name="job_description_id" type="text" value="11"></div>
                        <div style="display:none;"><input id="company_id" name="company_id" type="text" value="3"></div>
                        <input class="apply-submit-btn" name="commit" type="submit" value="Submit Application">
                    </form>
                </div>
            </div>
        </div>
        <div class="dropdown">
            <button class="j-descrip-button thin job-dropdown-link" menu="refer">Refer A Friend</button>
            <div class="dropdown-menu right refer-menu">
                <div class="dd_arrow"></div>
                <div class="refer-dropdown-content">
                    <form accept-charset="UTF-8" action="/send_refer_a_friend_email" html="{:role=>&quot;form&quot;}" method="post" class="ng-pristine ng-valid"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓"><input name="authenticity_token" type="hidden" value="tPFqDeHakW85TmdouG7Qsu9vJ5f+kvpM40MC2rYUPe0="></div>
                        <div class="form-group" style="display: none;">
                            <label for="company_name">Company Name</label>
                            <input class="form-control" id="company_name" name="company_name" type="text" value="Ice 2 Go">
                        </div>
                        <div class="form-group" style="display:none;">
                            <label for="job_title">Job Title</label>
                            <input id="job_title" name="Ruby Ninja" type="text" class="form-control">
                        </div>
                        <div style="font-size: 20px; margin-bottom: 10px;"><b>You're an awesome friend!</b></div>
                        <div class="form-group">
                            <label for="user_full_name">Your Name</label>  <!-- is this the best way to do this? -->
                            <div>
                                <input class="refer-text-field" id="user_full_name" name="user_full_name" type="text" value="Daniel Bonnell">
                            </div>
                        </div>
                        <div class="form-group">
                            <span><label for="friend_email">Your Friend's Email</label> <em style="font-size: 10px;">use commas for multiple emails</em></span>
                            <div>
                                <input class="refer-text-field" id="friend_email" name="friend_email" type="text">
                            </div>
                        </div>
                        <div class="prof-link" style="display: none;">
                            <label for="prof_link">Profile Link</label>
                            <input class="form-control" id="prof_link" name="prof_link" type="text" value="http://localhost:3000/ice-2-go">
                        </div>
                        <input class="refer-submit-btn" name="commit" type="submit" value="Send to My Friend(s)">
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

person Daniel Bonnell    schedule 03.06.2015    source источник


Ответы (2)


В следующий раз, когда вы зададите вопрос с таким большим количеством кода, может быть полезно создать jsfiddle, чтобы кто-то мог ответить на ваш вопрос быстрее и проще.

Я использовал визуализированный HTML-код, который вы предоставили, затем я немного изменил запрос, чтобы показать вам пару вещей, у этой кнопки есть только один брат (поэтому есть два jsfiddles, первый без .siblings(".apply-menu"), и я использовал .toggle() вместо .show(), поскольку, по крайней мере, в обработанном HTML он уже отображался.

Сценарий 1: http://jsfiddle.net/4t0nm1zt/1/

Сценарий 2: http://jsfiddle.net/4t0nm1zt/2/

Также обратите внимание на эту ссылку для братьев и сестер, в основном на уникальную часть братьев и сестер в первом примере / демонстрации, обратите внимание как написано 7, а не 11.

надеюсь, это поможет

person jbg    schedule 03.06.2015
comment
Думаю, виноват мой код Angular. Я попытался реализовать ваши предложения, которые мне понятны, но текстовое поле по-прежнему не отображается. Я скопировал / вставил части моего кода Angular, которые необходимы для рассматриваемого представления, в jsFiddle и смог воспроизвести проблему. Теперь, если вы нажмете кнопку «Применить», ничего не произойдет. - person Daniel Bonnell; 04.06.2015

Думаю, я понял проблему. В другом файле js у меня есть функция .click, привязанная к элементам с классом .dropdown-menu, который отменяет мою новую функцию щелчка. Смотрите код ниже:

$('.dropdown-menu').click(function(e) {
    e.stopPropagation();
});

$('.dropdown-link').click(function(e) {
    toggleDropdown(e, '#' + $(this).attr('menu'));
});

Я не знаю почему, но мне не пришло в голову просто скопировать все мои js файлы в jsFiddle и посмотреть, какой из них вызвал поломку.

person Daniel Bonnell    schedule 04.06.2015
comment
в этом случае лучший способ разрабатывать системы и тестировать проблемы - это делать их простыми, что не всегда легко. - person jbg; 04.06.2015
comment
Особенно, когда вы вносите изменения в систему, созданную кем-то другим. Не всегда понятно, что происходит на заднем плане. - person Daniel Bonnell; 04.06.2015