Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

javascript - innerHTML not working properly when used on a jQuery object

This code isn't working as expected. It is not showing any text inside of span.day where it should be showing today's day (Tuesday at the time of writing). It is also not properly adding the class "currentDay" inside of the $.each callback.

 $('#showLess span.day').innerHTML=weekday[today]; 

 $.each($('#showMore p span.day'), function(index, item) {  
      if(typeof item.innerHTML != 'undefined') 
      {     
           alert('item.text:' +item.innerHTML);
           alert('weekday[today]'+item.innerHTML.indexOf(weekday[today])); 

           if(item.innerHTML.indexOf(weekday[today])!=-1) { 
                alert("check which element has added class currentDay:");
                item.addClass('currentDay');
           }else{
                if(item.hasClass('currentDay')) {
                     item.removeClass('currentDay'); 
                }
           }
      } 
 });

.innerHTML is not changing the HTML, additional class is not getting added as expected.

<p id="showLess" class="less">
        <span class="day">**Tuesday**</span>
</p>

Why isn't the day showing?

Why is the show/hide not working?

$('.less').on('click', function(e) {
            $('#showMore').show();
            $('#showLess').hide();
        });

        $('.more').bind('click', function(e) {
            $('#showLess').show();
            $('#showMore').hide();
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are trying to invoke JS properties on jQuery objects.

For example innerHTML

And you are trying to invoke that on a jQuery object.

$('#showLessHours span.day').innerHTML

Should be

$('#showLessHours span.day')[0].innerHTML

or

$('#showLessHours span.day').html(weekday[today]);

And in your each loop item is a JS object and you are trying to add a class using jQuery. Convert that to jQuery object first .

item.addClass('currentDay');
item.removeClass('currentDay');

should be

$(item).addClass('currentDay');  or $(this).addClass('currentDay');
$(item).removeClass('currentDay'); or $(this).removeClass('currentDay')

Instead you can use the $(this) as well instead of $(item) object inside the callback as both refer to the same objects.

Another small suggestion is why do you want to mix vanilla JS and jQuery when jQuery is included and you want to use that in your application.

jsFiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...