jQuery - 使用 onclick 事件修改元素
jQuery - Modify element with onclick Event
这是 "almighty code"!
function testFun(target){
$(this).addClass("element")
$(target).addClass("target")
}
<a href="#" onclick="testFun('.class')" >Element</a>
<div class="class"> </div>
简而言之,我也想在 onClick 事件上修改元素!
我希望能够在多种情况下使用相同的功能。
请提供能够执行上述操作的解决方案。
问题是因为您的 testFun()
函数中的 this
没有引用调用该函数的元素 - 您需要传入 this
:[=16= 的引用]
function testFun(element, target) {
$(element).addClass("element")
$(target).addClass("target")
}
.element {
color: red;
}
.target {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="testFun(this, '.class')">Target</a>
<div class="class">Target</div>
这是 "almighty code"!
function testFun(target){
$(this).addClass("element")
$(target).addClass("target")
}
<a href="#" onclick="testFun('.class')" >Element</a>
<div class="class"> </div>
简而言之,我也想在 onClick 事件上修改元素! 我希望能够在多种情况下使用相同的功能。 请提供能够执行上述操作的解决方案。
问题是因为您的 testFun()
函数中的 this
没有引用调用该函数的元素 - 您需要传入 this
:[=16= 的引用]
function testFun(element, target) {
$(element).addClass("element")
$(target).addClass("target")
}
.element {
color: red;
}
.target {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" onclick="testFun(this, '.class')">Target</a>
<div class="class">Target</div>