我需要检查json字段是否为空如果不是空的显示内容我所拥有的似乎不起作用
<script src="http://mywebsite.com/benefits/?json=get_recent_posts&callback=listBenefits" > </script>
<script>
function listBenefits(data) {
$.each(data.posts, function(key, val) {
if ( val.length !== 0 ) {
output += '<li>' + val.custom_fields.extra_content_extra_content_second_value + "</li>";
}
if (val.length !== 0 ) {
output += '<li>' + val.custom_fields.extra_content_extra_content_third_value + "</li>";
}
});
}
</script>
json url output
object {5}
status : ok
count : 10
count_total : 10
pages : 1
posts [10]
custom_fields
extra_content_extra_content_third_value
我也试过这个
if (jQuery.isEmptyObject (val.custom_fields.extra_content_extra_content_third_value)) {
output += '<li>' + val.custom_fields.extra_content_extra_content_third_value + "</li>";
}
这是原始代码,如果没有值,我只需要列表不显示
output += '<li>' + val.custom_fields.extra_content_extra_content_third_value + "</li>";
答案 0 :(得分:0)
编辑:相反,我会在您的代码之后尝试这个偷偷摸摸的一个班轮:
$('li').each(function(){if ($(this).html().length == 0) $(this).remove()});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>hello</li>
<li>hey</li>
<li></li>
<li>get off my cloud</li>
</ul>
&#13;
答案 1 :(得分:0)
以下情况如何?
//don't forget to initialize output variable
var output = '';
//check if data is defined and that it has posts key
if( data && data.posts ) {
$.each(data.posts, function(key, val) {
//check if the loooooooong key has some data -- string
if( val.custom_fields.extra_content_extra_content_second_value.trim().length ) {
//your code here
}
});
}