我有这个代码:
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/