Автоматически нажмите также 2-ую кнопку при нажатии 1-й кнопки - PullRequest
1 голос
/ 08 ноября 2019

У меня проблема с нажатием кнопок. Что мне нужно, так это чтобы автоматически нажимать 2-ю кнопку, когда я нажимаю 1-ю кнопку .. Я создал пример кода, который не работает

HTML

<button id="button1" class="btn btn-success">1st button</button>
<a id="button2" class="btn btn-success" href="google.com">2nd button</a>

jQuery

   jQuery(document).ready(function() {
    jQuery('#button1').click(function () {
      jQuery('#button2').click();
   })
   });

Вот мой jdfiddle https://jsfiddle.net/wj8pb9sf/

Ответы [ 2 ]

1 голос
/ 08 ноября 2019

$("#button1").click(function(){ $("#button2").click(); });

А также вы не можете ввести href в кнопку.

1 голос
/ 08 ноября 2019

Этот фрагмент кода у меня уже довольно давно, и он зарекомендовал себя очень полезным в следующих ситуациях:

// Simulate event
function fireEvent(node, eventName) {
    // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
    var doc;
    if (node.ownerDocument) {
        doc = node.ownerDocument;
    } else if (node.nodeType == 9){
        // the node may be the document itself, nodeType 9 = DOCUMENT_NODE
        doc = node;
    } else {
        throw new Error("Invalid node passed to fireEvent: " + node.id);
    }

    if (node.dispatchEvent) {
        // Gecko-style approach (now the standard) takes more work
        var eventClass = "";

        // Different events have different event classes.
        // If this switch statement can't map an eventName to an eventClass,
        // the event firing is going to fail.
        switch (eventName) {
            case "click": // Dispatching of 'click' appears to not work correctly in Safari. Use 'mousedown' or 'mouseup' instead.
            case "mousedown":
            case "mouseup":
                eventClass = "MouseEvents";
                break;

            case "focus":
            case "change":
            case "blur":
            case "select":
                eventClass = "HTMLEvents";
                break;

            default:
                throw "fireEvent: Couldn't find an event class for event '" + eventName + "'.";
                break;
        }
        var event = doc.createEvent(eventClass);
        event.initEvent(eventName, true, true); // All events created as bubbling and cancelable.

        event.synthetic = true; // allow detection of synthetic events
        // The second parameter says go ahead with the default action
        node.dispatchEvent(event, true);
    } else  if (node.fireEvent) {
        // IE-old school style, you can drop this if you don't need to support IE8 and lower
        var event = doc.createEventObject();
        event.synthetic = true; // allow detection of synthetic events
        node.fireEvent("on" + eventName, event);
    }
};

Он не зависит от jQuery и позволяет вам моделировать кучуполезных событий. Просто сделайте: fireEvent(document.getElementById('button2'), 'click');.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...