如何在点击链接时更改 img div 边框的颜色?并且文本返回到“未选择点击”?
$('.div').click(function() {
if ( !($(this).hasClass('selected')) ) {
$(this).addClass('selected');
$(this.nextElementSibling).text('selected text');
} else {
$(this).removeClass('selected');
$(this.nextElementSibling).text('not selected');
}
});
.div {
width: 100px;
height: 100px;
border: 1px solid blue;
cursor: pointer;
}
.selected {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a> </p>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a></p>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a></p>
最佳答案
这是一个基于您已经使用的解决方案的快速解决方案。该链接嵌入在 p
中,因此您必须使用 parent()
,而 prev()
是等同于 nextElementSibling 的 jQuery
并返回一个 jQuery 对象。
你可以注意到我使用了 $('body').on('click', 'a.clicked', function)
而不是 $('a.clicked') .click(function)
,以防您想在文本中动态添加链接。使用click
,只有那些已经出现在页面加载中的才会被定位。使用 on('click')
,动态创建的元素也将如此。
请注意,您的解决方案依赖于元素位置,这可能不是最安全的做法。使用带有类的包装器来访问类中的所有元素会好一点。
$('.div').click(function() {
if ( !($(this).hasClass('selected')) ) {
$(this).addClass('selected');
$(this.nextElementSibling).text('selected text');
} else {
$(this).removeClass('selected');
$(this.nextElementSibling).text('not selected');
}
});
$('body').on('click', 'a.clicked', function(e) {
e.preventDefault();
if ( !($(this).parent().prev().hasClass('selected')) ) {
$(this).parent().prev().addClass('selected');
$(this).parent().text('selected text');
} else {
$(this).parent().prev().removeClass('selected');
$(this).parent().text('not selected');
}
});
.div {
width: 100px;
height: 100px;
border: 1px solid blue;
cursor: pointer;
}
.selected {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a> </p>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a></p>
<div class="div" style="background: url(http://lorempixel.com/output/people-q-c-640-480-1.jpg)"></div><p class="p">not selected <a href="#" class="clicked">Click</a></p>
关于javascript - 如何使单击链接时边框的颜色发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48278544/