不明白为什么.remove()无法正常工作

时间:2015-06-01 07:18:34

标签: javascript jquery html

您好我正在学习jQuery,我不明白为什么这个功能不起作用。当我点击按钮时,它应该删除div,但它不会。

删除功能

webView = (WebView) findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent,
                    String contentDisposition, String mimetype,
                    long contentLength) {
                // TODO Auto-generated method stub
                Toast.makeText(getApplicationContext(), "YES", Toast.LENGTH_SHORT).show();
                Request request = new Request(
                        Uri.parse(url));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_HIDDEN);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "download"); 
                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
                dm.enqueue(request);   

            }
        });

创建div的函数

$(".editButton").click(function () {
    $(".editButton").remove();
});

3 个答案:

答案 0 :(得分:3)

目前您正在使用直接绑定,这在代码进行事件绑定调用时页面上存在元素时有效。

您需要使用Event Delegation委托事件方法{。}}来使用.on()

$(document).on('event','selector',callback_function)

使用

如果您只想删除按钮

$(document).on('click', '.editButton', function () {
    $(this).remove(); 
});

如果要删除完整的帖子,首先,您需要在当前元素上下文中执行操作,因此请使用this。 然后使用closest()查找post个父级,然后使用.remove()

$(document).on('click', '.editButton', function () {
    $(this).closest('.post').remove(); 
});

答案 1 :(得分:1)

使用活动委派

您动态添加了编辑按钮。 DOM不知道元素何时被添加,所以我们需要遍历文档或正文或者直接父选择器来查找元素

$(document).on('click', '.editButton', function () {
    $(this).remove();
});

答案 2 :(得分:1)

由于您正在动态创建div,请使用事件委派

$(document).on('click', '.editButton', function () {
    $(this).remove();
});
相关问题