在jQuery对象上使用时,innerHTML无法正常工作 [英] innerHTML not working properly when used on a jQuery object

查看:97
本文介绍了在jQuery对象上使用时,innerHTML无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码未按预期运行。它没有在span.day内显示任何文本,它应该显示今天的日期(写作时的星期二)。它也没有在 $。每个回调中添加currentDay类。

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 不会更改HTML,额外的课程没有按预期添加。

.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>

为什么不显示这一天?

为什么show / hide不起作用?

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();
        });


推荐答案

您正在尝试在jQuery对象上调用JS属性。

You are trying to invoke JS properties on jQuery objects.

例如 innerHTML

你正在尝试在jQuery对象上调用它。

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

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

应该是

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

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

并且在每个循环中 item 是一个JS对象,您正在尝试使用jQuery添加一个类。首先将其转换为jQuery对象。

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');

应该是

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

相反,你可以使用 $(this)以及回调中的 $(item)对象,因为它们都引用相同的对象。

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

另一个小建议是,为什么你想在包含jQuery时混合使用vanilla JS和jQuery,并且你想在你的应用程序中使用它。

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

jsFiddle

这篇关于在jQuery对象上使用时,innerHTML无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆