我是jQuery的新手,我无法看到我的代码出错的地方。我正在尝试使用id
custom-logo-video
获取一个元素,以使用if语句更改其innerHTML
(如果它是""或空白等)。但它不起作用。我做错了什么?
$(document).ready(function(){
var a = $("#custom-logo-video");
if (!a.trim()) {
// is empty or whitespace
a.innerHTML("easy");
} else {
a.innerHTML("hard");
}
});
答案 0 :(得分:1)
你可以尝试:
$(document).ready(function () {
var a = $('#custom-logo-video').html();
if (!$.trim(a)) {
// is empty or whitespace
$('#custom-logo-video').html("easy");
} else {
$('#custom-logo-video').html("hard");
}
});
答案 1 :(得分:0)
您正在使用innerHTML
,因为您正在使用jQuery,所以这不是必需的。 .html()
就足够了。
试试这个:
$(document).ready(function(){
var a = $("#custom-logo-video");
if ( !a.html().trim() ) {
// is empty or whitespace
a.html('easy');
}
else {
a.html('hard');
}
});
编辑:修复了代码中的拼写错误和逻辑。
答案 2 :(得分:0)
试试这段代码:
$(document).ready(function(){
var a = $("#custom-logo-video");
// To check if the node is empty or not I am
// calling jQuery api is(':empty')
if (a.is(':empty')) {
// is empty or whitespace
// To replace the innerHTML of a node you call a .html() jQuery api
a.html("easy");
} else {
a.html("hard");
}
});
答案 3 :(得分:0)
代码的一些问题
var a = $(#custom-logo-video);
选择需要它周围的引号
var a = $('#custom-logo-video');
当你使用jquery进行选择时,你有一个jQuery对象,所以innerHTML不起作用,你想使用.html()或.text()来获取内部文本。以下是我修复它的方法。
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.html()) {
// is empty or whitespace
a.html("easy");
}else{
a.html("hard");
}
});
您可以在此处阅读更多内容:https://learn.jquery.com/using-jquery-core/selecting-elements/
答案 4 :(得分:0)
试试这个:
$(document).ready(function(){
var a = $('#custom-logo-video');
if (!a.trim()) {
// is empty or whitespace
a.text("easy");
} else {
a.text("hard");
}
});
答案 5 :(得分:0)
试试这个,
$(document).ready(function () {
var a = $('#custom-logo-video').html();
(a !== null && a.trim().length > 0) ? a.html('hard') : a.html('easy');
});