当单击LINKS之一时,如何更改此div的内容?
<div align="center" id="content-container">
<a href="#" class="click cgreen">Main Balance</a>
<a href="#" class="click cgreen">PayPal</a>
<a href="#" class="click cgreen">AlertPay</a>
</div>
Answers:
您可以订阅链接的.click事件,并使用以下.html方法更改div的内容:
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').html(linkText);
// cancel the default action of the link by returning false
return false;
});
但是请注意,如果替换此div的内容,则分配给您的点击处理程序将被销毁。如果打算在div中注入一些新的DOM元素(需要为其添加事件处理程序),则应在插入新内容后在.click处理程序内执行此附件。如果保留了事件的原始选择器,则还可以查看.delegate附加处理程序的方法。
$('#content-container').html($('#someOtherDivId').html());
您将在这里使用2个jQuery函数。
1)click。这将使用匿名函数作为唯一参数,并在单击元素时执行它。
2)html。这将使用html字符串作为唯一参数,并将元素的内容替换为提供的html。
因此,根据您的情况,您需要执行以下操作:
$('#content-container a').click(function(e){
$(this).parent().html('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
如果您只想向div添加内容,而不是替换其中的所有内容,则应使用append:
$('#content-container a').click(function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
如果希望新添加的链接在单击时也添加新内容,则应使用事件委托:
$('#content-container').on('click', 'a', function(e){
$(this).parent().append('<a href="#">I\'m a new link</a>');
e.preventDefault();
});
您可以使用replacewith()尝试相同的操作
$('.click').click(function() {
// get the contents of the link that was clicked
var linkText = $(this).text();
// replace the contents of the div with the link text
$('#content-container').replaceWith(linkText);
// cancel the default action of the link by returning false
return false;
});
该.replaceWith()方法从DOM中删除内容,并通过一次调用将新内容插入其位置。
尝试使用jQuery更改div的内容。
查看更多@使用jQuery更改div的内容
$(document).ready(function(){
$("#Textarea").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$(".output").text(currentText);
});
});
尝试 $('#score_here').html=total;