[英]JQuery not adding class on click
I'm struggeling with some code, I have code to when I click a <p>
element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element. 我正在努力处理一些代码,当我单击
<p>
元素时,它具有更改iframe src的代码,并删除了.html文件中所有元素的“活动”类,然后将“活动”类添加到单击的元素。
But the class 'active' never gets added to the clicked element. 但是,“活动”类永远不会添加到clicked元素中。
JAVASCRIPT JAVASCRIPT
function loadIframe(url){
$('.iframe_settings').attr('src', url);
$('.nav li').removeClass('active');
$(this).addClass('active');
};
HTML 的HTML
<li class="w-100" id="http://whatever.com/" onclick="return loadIframe(this.id);">
<p>
<i class="fa fa-id-badge" aria-hidden="true"></i>
<span class="nav-label">Intranet</span>
</p>
</li>
you could pass the context (element) to the handler. 您可以将上下文(元素)传递给处理程序。 I expect this to work:
我希望这可以工作:
loadIframe(this.id, this)
And, 和,
function loadIframe(url, element){
$('.iframe_settings').attr('src', url);
$('.nav li').removeClass('active');
$(element).addClass('active');
};
Let me know if that works for you. 让我知道这是否适合您。
Stray comment: I am not sure if it is a good practice to call url an id. 流浪评论:我不确定将url称为id是否是一个好习惯。 You might find data-attributes useful.
您可能会发现数据属性很有用。 Attributes like
data-id = ""
. 像
data-id = ""
这样的属性。 In fact I would call it data-url
. 实际上,我将其称为
data-url
。
You need to correct your code add identifier in correct way. 您需要以正确的方式更正代码添加标识符。
function loadIframe(url){
$('.iframe_settings').attr('src', url);
$('.nav li').removeClass('active');
$("#"+url).addClass('active');
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.