简体   繁体   English

如何使用div的title属性添加类?

[英]How to use the title attribute of a div to add a class?

I'm trying to add a class to a div by using the title attribute. 我正在尝试通过使用title属性将一个类添加到div中。 Currently the alert is correct. 当前警报是正确的。 However the class isn't added. 但是,未添加该类。

JS Part: JS部分:

function index(clicked_id){
   alert(clicked_id);
   $('#sticky').attr("title", +clicked_id).addClass("glow");
}

HTML Part: HTML部分:

<div id="sticky" class="" title='sticky1' onclick='index(this.title)'</div>"

I don't know if I got your question right but I understood that you want to filter|find you div by the title. 我不知道您的问题是否对,但我知道您想按标题过滤div。 So maybe this code will help you: 因此,也许这段代码可以帮助您:

function index(clicked_id){
   alert(clicked_id);
   $('#sticky [title="' + clicked_id + '"]').addClass("glow");
}

This is how I would do it: 这就是我要做的:

$("[title*='sticky']").click(function(){
    $(this).addClass("glow");
});

Here is the JSFiddle demo 这是JSFiddle演示

Instead just pass this : 相反,只需传递this

onclick='index(this)'  

now in the function: 现在在函数中:

function index(el){
   var e = $(el).attr('title');
   $('#sticky[title="'+e+'"]').addClass("glow");
}

As the element itself is the target one then just use this: 由于元素本身就是目标,因此只需使用以下命令:

function index(el){
   $(el).addClass("glow");
}

or better to go unobtrusive, remove the inline event handler and use this way: 或更好一些,以消除干扰,请删除内联事件处理程序并使用以下方式:

$('#sticky').on('click', function(e){
    $(this).addClass("glow");
});

Why do you need to do it like that? 为什么需要那样做? Can't you just set the class on the element clicked? 您不能仅对所单击的元素设置类吗?

JavaScript 的JavaScript

function index(el){
    $(el).addClass("glow");
}

HTML HTML

<div id="sticky" onclick='index(this)'></div>

js at Question returns expected results. Question上的js返回预期结果。 Missing closing > at html #sticky <div> tag at html #sticky <div>标记处缺少结束>

onclick="index(this.title)"

following onclick attribute . 跟随onclick属性。 Additionally, 另外,

+ 

should be removed at 应该在删除

+clicked_id

at .attr() setting title . .attr()设置title javascript + operator attempting to convert clicked_id String to Number when placed before string javascript +运算符,尝试将clicked_id String转换为Number置于字符串之前)

 function index(clicked_id){ alert(clicked_id); $('#sticky').attr("title", clicked_id).addClass("glow"); } 
 .glow { color: purple; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <div id="sticky" class="" title="sticky1" onclick="index(this.title)">click</div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM