javascript - 如何获取 "this"的值?

标签 javascript jquery

我有这个代码:

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]。

如果我在 div 中单击它,我希望 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 链接 is here .

关于javascript - 如何获取 "this"的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14929357/

相关文章:

php - 如何将 html 元素值提交给其在 Kohana 中的相应 Controller

jquery - 如何在单击添加类时翻转元素?

jquery - 使用 jQuery 将列表框项目移动到另一个列表框

javascript - jQuery keydown 事件禁用

javascript - 收到错误 Uncaught TypeError : Cannot set property 'value' of null

javascript - Jquery数据表的页数

javascript - 如何在 JavaScript 中使用异步生成器?

javascript - Css3 slider 多图像

javascript - 返回一个函数(来自 Stoyan Stefanov 的《面向对象的 JavaScript》第 95 页)

javascript - 如何使用 css/Extjs 在悬停在另一个元素上时显示一个元素