如何获取“;这个“;

How to get value of "this"?

本文关键字:这个 获取 何获取      更新时间:2023-09-26

我有这个代码:

HTML:

<!DOCTYPE html>
<html>
    <head>
        <title>To Do</title>
        <link rel="stylesheet" type="text/css" href="stylesheet.css"/>
        <script type="text/javascript" src="script.js"></script>
    </head>
    <body>
        <h2>To Do</h2>
        <form name="checkListForm">
            <input type="text" name="checkListItem"/>
        </form>
        <div id="button">Add!</div>
        <br/>
        <div class="list"></div>
    </body>
</html>

Javascript/Jquery:

$(document).ready(function()
{
 $(button).click(function(){
  var toAdd = $('input[name=checkListItem]').val();
  $('.list').append('<div class="item">' + toAdd + '</div>');
 });
 $(document).on('click','.item', function(){
   $(this).remove();
  });
});

这段代码获取用户的输入,当您单击按钮时将其添加到列表中,当您在div类项中单击输入时将其从列表中删除。

我如何才能返回"this"的值?

例如,如果我将单词"test"添加到列表中,然后单击它将其删除……如何从"this"中获取test的值?

比如。。document.write(this)返回[object HTMLDivElement]。

如果我在分区中点击document.write,我希望它返回"test"。

我不能执行document.write(toAdd),因为toAdd在第二个jquery("on")函数中不存在。谢谢

$(document).ready(function () {
    $('#button').on('click', function () {
        var toAdd = $('input[name=checkListItem]').val();
        $('.list').append('<div class="item">' + toAdd + '</div>');
    });
    $(document).on('click', '.item', function () {
        alert( $(this).text() ); // You can have `.html()` here too.
        $(this).remove();
    });
});

Fiddle链接在这里。

使用.innerHTML:

$(document).ready(function()
{
 $(button).click(function(){
  var toAdd = $('input[name=checkListItem]').val();
  $('.list').append('<div class="item">' + toAdd + '</div>');
 });
 $(document).on('click','.item', function(){
   document.write(this.innerHTML);
   $(this).remove();
  });
});

您可以通过$(this).text()检索单击项目中的文本。因此,在删除项目之前,可以执行类似document.write($(this).text())的操作。