Javascript 使用this.addClass(Jquery)

Javascript 使用this.addClass(Jquery),javascript,jquery,Javascript,Jquery,我正在jquery中尝试this.addclass向DIV添加一个类,这可能是未知的。这样能解决这个问题吗 <style>.classOne { font-size:24px; color:#009900;}</style> <script> function hello() { alert(); $(this).addClass('classOne'); } </script> <div class="something" onc

我正在jquery中尝试this.addclass向DIV添加一个类,这可能是未知的。这样能解决这个问题吗

<style>.classOne { font-size:24px; color:#009900;}</style>

<script>
function hello()
{   alert();
$(this).addClass('classOne');
}
</script>

<div class="something"  onclick="hello();"> Test information </div>
.classOne{字体大小:24px;颜色:#009900;}
函数hello()
{alert();
$(this.addClass('classOne');
}
测试信息
您对“this”的引用无效,请尝试此选项

<style>.classOne { font-size:24px; color:#009900;}</style>

<script>
function hello(ojecttRef)
{   alert();
$(ojecttRef).addClass('classOne');
}
</script>

<div class="something"  onclick="hello(this);"> Test information </div>
.classOne{字体大小:24px;颜色:#009900;}
函数hello(OJECTREF)
{alert();
$(ojecttRef).addClass('classOne');
}
测试信息

这样会更好

//Bind a click event to the div
$('div').on('click', function(){
     $(this).addClass('classOne');
});

//No Onclick needed here
<div class="something"> Stuff Here </div>
//将单击事件绑定到div
$('div')。在('click',function()上{
$(this.addClass('classOne');
});
//这里不需要点击
这里的东西

尽可能避免使用内联javascript,而是执行以下操作:

<style>.classOne { font-size:24px; color:#009900;}</style>

<script type="text/javascript">
$(function() {
    $('.something').on('click', function() {
        alert('hello');
        $(this).addClass('classOne');
    });
});
</script>

<div class="something"> Test information </div>
.classOne{字体大小:24px;颜色:#009900;}
$(函数(){
$('.something')。在('click',function()上{
警惕(“你好”);
$(this.addClass('classOne');
});
});
测试信息
使用
$('this').addClass('classOne')取而代之


这个
本身不能单独运行。在提问之前,需要在
$()

一个测试东西的好地方…我想-我不能确切地说,他想在许多div中添加这个函数,除了“.somthing”“尽可能避免内联javascript”,为什么?内联一直存在,它的速度更快,调试也更容易。我使用尽可能多的内联代码,而不是使用50000行代码进行过滤。你是我见过的第二个这么说的人,我还是不明白为什么。也许我只是对你们这些年轻的快速阅读者来说是老派的,哈哈。更多的代码行=更多的废话要读=我和PCNot都要处理更长的时间。更不用说,jQuery的关键特性之一“链接”,是专为“内联”编码而设计的。你为什么反对这个?哦,NM!我刚得到你想要的东西,我在想代码中的内联,而不是元素,facepalm愚蠢的时刻!你说对了!内联JS是指HTML中的内联,即在HTML中使用onmouseover、onclick等。它没有什么真正的问题,但是现在分离功能、外观和布局会使事情变得更容易,而且在分离的文件中使用javascript和样式几乎总是一种方法。另一方面,链接当然很好,它是任何javascript库的核心特性之一。