使用jquery" .off"删除一个事件处理程序。

时间:2016-07-04 04:10:56

标签: javascript jquery twitter-bootstrap

我从某个地方借用了这个代码,从一个bootstrap模式切换到另一个模式。切换后,我想关闭处理程序,这样每次关闭第一个模态时它都不会切换。我的问题是,一旦使用模态切换功能,我不知道如何关闭该特定事件处理程序而不关闭当某个模态关闭时我触发的其他事件(在别处完成)。有什么建议吗?

//switch modals
function switchModals(fromModal, toModal) {
    $(fromModal).on('hidden.bs.modal', function (e) {
        $(toModal).modal('show');
        //clear this function so it doesn't show up if they exit the window again
        $(fromModal).off('hidden.bs.modal');
    });
    $(fromModal).modal('hide');
}

4 个答案:

答案 0 :(得分:1)

您需要将此行放在switchModals

之外
$(<FromModalId>).modal('hide');

答案 1 :(得分:0)

尝试在 HistoryHelper file = new HistoryHelper(view.getContext()); file.writeToSD(url.substring('\n')); 回调中使用public class HistoryHelper { String TAG = "MyFile"; Context context; public HistoryHelper(Context context) { this.context = context; } public Boolean writeToSD(String text) { Boolean write_successful = false; File root = null; try { // check for SDcard root = Environment.getExternalStorageDirectory(); Log.i(TAG, "path.." + root.getAbsolutePath()); // check sdcard permission if (root.canWrite()) { File fileDir = new File( Environment.getExternalStorageDirectory() + "/AVD/"); fileDir.mkdirs(); File file = new File(fileDir, "History.txt"); FileWriter filewriter = new FileWriter(file); BufferedWriter out = new BufferedWriter(filewriter); out.write(text); out.close(); write_successful = true; Toast.makeText(context, "success!", Toast.LENGTH_LONG).show(); } } catch (IOException e) { Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage()); write_successful = false; Toast.makeText(context, "operation failed!", Toast.LENGTH_LONG) .show(); } return write_successful; } } 代替this,例如

fromModal

答案 2 :(得分:0)

请尝试以下方法在模态之间切换:

    var el = fromModal+','+toModal;
    $(el).on('hidden.bs.modal', function (e) {
        $(el).not(this).modal('show');
        $(this).modal('hide');
    });

答案 3 :(得分:0)

我找到了解决方案。我只需要为处理程序提供一个对该函数唯一的命名空间。然后我通过“.off()”方法中的命名空间解除绑定。我选择“switch”作为命名空间。

//switch modals
function switchModals(fromModal, toModal) {
    $(fromModal).on('hidden.bs.modal.switch', function (e) {
        $(toModal).modal('show');
        //clear this function so it doesn't show up if they exit the window again
        $(fromModal).off('.switch');
    });
    $(fromModal).modal('hide');
}