[英]javascript/HTML: Bind event handler function with object as argument in HTML string literal
[英]jQuery .html() method function literal argument
為什么下面的兩個語句不能完成相同的事情?
$('li.list1').html(function() {
return '<em>' + $(this).text() + '</em>';
});
和:
$('li.list1').html('<em>' + $(this).text() + '</em>');
根據文檔, .html()
回調用於替換所選元素的內容時會清空它。
如果在回調中使用function
,則會返回兩個參數:元素的index
及其當前內容(清空之前)。
因此,您可以這樣做:
$('li.list1').html(function (index, oldHtml) {
return '<em>' + oldHtml+ '</em>';
});
$(function () { $('li.list1').html(function (index, data) { return '<em>' + data + '</em>'; }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="list1">Text</li> </ul>
這種方式行不通: $('li.list1').html('<em>' + $(this).text() + '</em>');
$(this)
這里指的是jQuery對象Window
,除非它在某種包裝器之內,例如事件處理程序:
$('li.list1').on('click', function () {
$(this).html('<em>' + $(this).text() + '</em>');
});
$(function () { $('li.list1').on('click', function () { $(this).html('<em>' + $(this).text() + '</em>'); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li class="list1">Text</li> </ul>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.