有没有办法切换title
的{{1}}属性值?
好像文字标题在<i>
<i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true">
我想用下面给出的代码切换标题文本及其类:
<div class="postoption">
答案 0 :(得分:3)
您可以使用以下简单条件来实现此功能:
var target = $(this).find('i');
if( target.attr('title') == "Remove Favorite" )
target.attr('title', "Favorite This Post");
else
target.attr('title', "Remove Favorite");
希望这有帮助。
$('.postoption').click(function() {
$(this).find('i').toggleClass('fa-star-o fa-star');
var target = $(this).find('i');
if (target.attr('title') == "Remove Favorite")
target.attr('title', "Favorite This Post");
else
target.attr('title', "Remove Favorite");
});
<link href="https://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="postoption">
<i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true"></i>
</div>
答案 1 :(得分:1)
使用attr()
访问标题值,然后切换它。
$('.postoption').click(function() {
$(this).find('i').toggleClass('fa-star-o fa-star');
var title = $(this).find('i');
//just check the value of title and toggle the value
console.log(title.attr("title"));
if(title.attr("title") === "Favorite This Post"){
title.attr("title", "Remove This Post");
}
else{
title.attr("title", "Favorite This Post");
}
});
.postoption{
background: #ccc;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="postoption">
<i title="Favorite This Post" class="fa fa-star-o" aria-hidden="true">Icon</i>
</div>
答案 2 :(得分:1)
No-Jquery解决方案
<!DOCTYPE html>
<html>
<body>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<i id='iTag' class="red" title="Favorite This Post"></i>
<button id="toggleButton" type="button"> Toggle title</button>
<script type="text/javascript">
document.getElementById('toggleButton').onclick = function(){
var iTag = document.getElementById('iTag'),
iTagTitle = iTag.getAttribute('title');
if(iTagTitle == 'Favorite This Post') {
iTag.setAttribute('title','Remove This Post');
}
else {
iTag.setAttribute('title','Favorite This Post');
}
};
</script>
</body>
</html>