DIV CSS 佈局教程網

如何在 onclick 事件中取得 JavaScript 函式的回傳值
編輯:JavaScript基礎知識     

動態建立彈跳視窗時,常見需求是:使用者點了「確定」或「取消」,外層程式要能拿到對應結果。但直接把函式綁到 onclick 上,回傳值似乎不受控制。問題出在事件處理函式的回傳值有它自己的語義。

一、問題重現

function createBtn() {
    for (var i = 0; i < _this.btn.length; i++) {
        var btn = document.createElement('span');
        btn.id = 'btn_' + i;
        btn.innerHTML = _this.btn[i];
        btn.style.padding = '5px 15px';
        btn.style.background = '#E5E5E5';
        btn.style.borderRadius = '5px';
        btn.style.marginRight = '15px';
        btn.style.cursor = 'pointer';
        document.getElementById('btn_box').appendChild(btn);
        // btn.onclick = closeBox;
    }
}

function closeBox() {
    var box = document.getElementById('msg_box');
    box.remove();
    if (this.id == 'btn_0') {
        isBool = true;
    } else {
        isBool = false;
    }
    return isBool;
}

這段程式碼的問題在於:onclick 的回傳值只被用來決定「是否攔截預設行為」,不會傳回給任何外層程式。也就是說,return false 會阻止表單提交或連結跳轉,而 return true 只是允許預設行為發生,兩者都無法作為「查詢結果」的通道。

二、正確思路:用回呼或 Promise 傳遞結果

既然回傳值走不通,就改用參數傳遞。最直覺的是回呼函式:

function openBox(buttons, callback) {
    var box = document.getElementById('msg_box');
    var btnBox = document.getElementById('btn_box');

    buttons.forEach(function (text, i) {
        var btn = document.createElement('button');
        btn.type = 'button';
        btn.textContent = text;
        btn.onclick = function () {
            box.remove();
            callback(i);   // 把使用者選擇傳出去
        };
        btnBox.appendChild(btn);
    });
}

// 呼叫端
openBox(['確定', '取消'], function (index) {
    var confirmed = index === 0;
    console.log('使用者選擇:', confirmed);
});

若偏好同步風格的寫法,用 Promise 更清爽:

function openBox(buttons) {
    return new Promise(function (resolve) {
        var box = document.getElementById('msg_box');
        var btnBox = document.getElementById('btn_box');

        buttons.forEach(function (text, i) {
            var btn = document.createElement('button');
            btn.type = 'button';
            btn.textContent = text;
            btn.onclick = function () {
                box.remove();
                resolve(i === 0);
            };
            btnBox.appendChild(btn);
        });
    });
}

// 呼叫端
openBox(['確定', '取消']).then(function (confirmed) {
    console.log('使用者選擇:', confirmed);
});

關鍵觀念是:事件處理函式是「被動應答」,它的回傳值有固定用途;要把資料往外傳,必須透過回呼、Promise 或事件觸發這類主動通道。順帶一提,範例中原本的 box.remove() 已改為標準 DOM 寫法,並把 isBool 宣告為區域變數,避免污染全域。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved