我在這里有這個很好的參考。我正在嘗試切換一個類,一次會影響 1 個。但是,如果不使用父元素來單擊,就像在參考中一樣,它似乎不起作用。我只想使用 1 個具有點擊功能的類,并且一次切換一個效果。這可能嗎?
$(document).ready(function() {
getQuoteButtton();
});
function getQuoteButtton() {
// button quote
$("body").on("click", ".btn-quote", function(e) {
var $this = $(this);
$this.toggleClass('quote-selected');
if ($this.hasClass('quote-selected')) {
$this.text('Selected');
} else {
$this.text('Select This Quote');
}
});
}
.section-block-table {
width: 100%;
margin: 0 auto;
position: relative;
border-collapse: separate;
color: #2E384D;
border-spacing: 0;
}
.btn-quote {
background: #fff;
position: relative;
text-align: center;
color: #49CD96;
font-size: 14px;
font-weight: 600;
line-height: 20px;
padding: 8px 9px;
border-radius: 6px;
border: 1px solid #49CD96;
min-width: 166px;
}
.btn-quote:hover {
background: #49CD96;
color: #fff;
}
.btn-quote.quote-selected {
background: #49CD96;
color: #fff;
}
.btn-quote.quote-selected:before {
content: "\f00c";
font-family: 'Font Awesome 5 Free';
color: #fff;
margin-right: 7px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table class="section-block-table">
<tr>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
</tr>
</table>
uj5u.com熱心網友回復:
建議委托。為什么不想使用父元素?
注意我添加了一個推薦的 tbody 并給了它一個 ID
$(function() {
getQuoteButtton()
})
function getQuoteButtton() {
const $tb = $("#tb");
$tb.on("click", ".btn-quote", function(e) {
$this = $(this);
$this
.toggleClass('quote-selected')
.text($this.hasClass('quote-selected') ? 'Selected' : 'Select This Quote');
$(".btn-quote", $tb).not(this)
.removeClass('quote-selected')
.text('Select This Quote');
});
}
.section-block-table {
width: 100%;
margin: 0 auto;
position: relative;
border-collapse: separate;
color: #2E384D;
border-spacing: 0;
}
.btn-quote {
background: #fff;
position: relative;
text-align: center;
color: #49CD96;
font-size: 14px;
font-weight: 600;
line-height: 20px;
padding: 8px 9px;
border-radius: 6px;
border: 1px solid #49CD96;
min-width: 166px;
}
.btn-quote:hover {
background: #49CD96;
color: #fff;
}
.btn-quote.quote-selected {
background: #49CD96;
color: #fff;
}
.btn-quote.quote-selected:before {
content: "\f00c";
font-family: 'Font Awesome 5 Free';
color: #fff;
margin-right: 7px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table class="section-block-table">
<tbody id="tb">
<tr>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
<td><button class="btn-quote m-auto">Select This Quote</button></td>
</tr>
</tbody>
</table>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361812.html
標籤:javascript 查询
