3

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

4 に答える 4

14

可能な限りインライン 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>

フィドル

于 2012-11-08T15:05:17.733 に答える
8

「これ」への言及は無効です。代わりにこれを試してください

<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>
于 2012-11-08T15:01:50.080 に答える
2

これはもっと良いでしょう...

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

//No Onclick needed here
<div class="something"> Stuff Here </div>
于 2012-11-08T15:02:57.337 に答える