我怎样才能做到以下几点:

document.all.regTitle.innerHTML = 'Hello World';

使用jQuery哪里regTitle是我的div id?


当前回答

以下是你的答案:

//This is the setter of the innerHTML property in jQuery
$('#regTitle').html('Hello World');

//This is the getter of the innerHTML property in jQuery
var helloWorld = $('#regTitle').html();

其他回答

$("#regTitle")[0].innerHTML = 'Hello World';

以下是你的答案:

//This is the setter of the innerHTML property in jQuery
$('#regTitle').html('Hello World');

//This is the getter of the innerHTML property in jQuery
var helloWorld = $('#regTitle').html();

已经有答案给出了如何改变元素的内部HTML。

但是我建议,你应该使用一些像渐隐/渐隐这样的动画来改变HTML,这给了改变HTML的良好效果,而不是立即改变内部HTML。

使用动画来改变内部HTML

$('#regTitle').fadeOut(500, function() {
    $(this).html('Hello World!').fadeIn(500);
});

如果你有很多函数需要这个,那么你可以调用通用函数来改变Html内部。

function changeInnerHtml(elementPath, newText){
    $(elementPath).fadeOut(500, function() {
        $(this).html(newText).fadeIn(500);
    });
}

只是添加一些性能见解。

几年前,我有一个项目,我们在试图将一个大的HTML / Text设置为各种HTML元素时遇到了问题。

看起来,“重新创建”元素并将其注入DOM比任何更新DOM内容的建议方法都要快得多。

比如:

Var文本= "非常大的内容"; $ (" # regTitle ") .remove (); $ (" < div id =“regTitle”>“+文字+ " < / div > ") .appendTo(“身体”); < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本>

应该能让你有更好的表现。我最近没有试着去衡量它(现在的浏览器应该很聪明),但是如果你在寻找性能,它可能会有帮助。

缺点是您需要做更多的工作来保持脚本中的DOM和引用指向正确的对象。

纯JS和最短

纯JS

regTitle.innerHTML = 'Hello World'

regTitle。innerHTML = 'Hello World'; < div id = " regTitle " > < / div >

最短的

$(regTitle).html('Hello World'); 

//注意:regTitle周围没有引号 $ (regTitle) . html(“Hello World”); < script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> < div id = " regTitle " > < / div >