首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在mouseleave事件上从<li>中删除文本

在mouseleave事件上从<li>中删除文本
EN

Stack Overflow用户
提问于 2018-06-07 07:19:56
回答 1查看 33关注 0票数 0

我有一台ul。当我将鼠标悬停在列表中的任何li上时,我正在做一些事情,而在鼠标离开时,我想做一些其他的事情。我仍然在使用jQuery。

问题出现在mouseleave事件发生的末尾。我基本上想撤消.hover事件执行的.append() ...

代码语言:javascript
复制
//for each li in #mylist...
$('#myList > li').each(function () {

    //get the li content...
    var liName = $(this)[0].innerText;

    //instantiate number
    var number;

    //instantiate formattedNumber
    var formattedNumber;

    //when hover over each li...
    $(this).hover(function () {

        //get a number from the div where liName is found...
        $('.square').each(function () {

            var name = $(this).find('tr:eq(0)').find('td').text();

            if (name === liName) {

                number = $(this).find('tr:eq(6)').find('td').text();

            }

        })

        //format the number...
        formattedNumber = ': ' + number.substring(0, 3) + '-' + number.substring(3, 6) + '-' + number.substring(6, 10)

        //append the formatted number to this li...
        $(this).append(formattedNumber);

        //when mouse leaves the li, remove the formatted number...
    }, function () {

        //this is what I cannot get working. I basically want to do the opposite on mouseleave and remove the just appended text...but leave the initial content of the li in place

    })

})
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-07 07:33:13

您可以将附加的文本包装在一个元素中,这样以后删除它就更容易了:

代码语言:javascript
复制
//for each li in #mylist...
$('#myList > li').each(function () {

    //get the li content...
    var liName = $(this)[0].innerText;

    //instantiate number
    var number;

    //instantiate formattedNumber
    var formattedNumber;

    //when hover over each li...
    $(this).hover(function () {

        //get a number from the div where liName is found...
        $('.square').each(function () {

            var name = $(this).find('tr:eq(0)').find('td').text();

            if (name === liName) {

                number = $(this).find('tr:eq(6)').find('td').text();

            }

        });

        //create a span and set its text to as format the number...
        formattedNumber = $('<span />').text(': ' + number.substring(0, 3) + '-' + number.substring(3, 6) + '-' + number.substring(6, 10));

        //append the formatted number to this li...
        $(this).append(formattedNumber);

        //when mouse leaves the li, remove the formatted number...
    }, function () {

        //remove the created span
        formattedNumber.remove();

    });

});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50730936

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档