仅选择单击元素的“this”对象(不是同一类中的其他元素)

时间:2018-02-21 10:03:23

标签: javascript this

我正在尝试在点击时更改按钮文本(使用Bootstrap 4)。我在使用正确的语法方面遇到了问题。

我的HTML:

<div class="btn-group">
  <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="dropdownMenuButton2">
  Option 1                  
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton2">
    <a class="dropdown-item" href="#">Option 2</a>
    <a class="dropdown-item" href="#">Option 3</a>
 </div>
</div>

<div class="btn-group">
  <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="dropdownMenuButton2">
  Type 1                  
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton3">
    <a class="dropdown-item" href="#">Type 2</a>
    <a class="dropdown-item" href="#">Type 3</a>
 </div>
</div>

和JS:

$(".dropdown-menu a").click(function () {

  $(".btn:first-child").html($(this).text());

});

改写 - 当我点击一个按钮并更改其值时,另一个按钮也会改变...

所以我想改变唯一点击的这个值。

3 个答案:

答案 0 :(得分:1)

您需要相对于您的链接更改html的{​​{1}}。

您可以选择距您的链接最近的.btn,然后在其中搜索.btn-group来执行此操作:

.btn

&#13;
&#13;
$(".dropdown-menu a").click(function () {
  $(this).closest('.btn-group').find('.btn').html($(this).text());
});
&#13;
$(".dropdown-menu a").click(function() {
  $(this).closest('.btn-group').find('.btn').html($(this).text());
});
&#13;
&#13;
&#13;

答案 1 :(得分:1)

&#13;
&#13;
$(".dropdown-menu a").click(function () {
  var text = $(this).text();
  $(this).closest('.btn-group').find('.btn').html(text);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="btn-group">
  <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="dropdownMenuButton2">
  Option 1                  
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton2">
    <a class="dropdown-item" href="#">Option 2</a>
    <a class="dropdown-item" href="#">Option 3</a>
 </div>
</div>

<div class="btn-group">
  <button type="button" class="btn btn-outline-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" id="dropdownMenuButton2">
  Type 1                  
  </button>
  <div class="dropdown-menu" aria-labelledby="dropdownMenuButton3">
    <a class="dropdown-item" href="#">Type 2</a>
    <a class="dropdown-item" href="#">Type 3</a>
 </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

尝试

Sub ComparerCP()
Dim ws1 As Worksheet: Set ws1 = Worksheets("Feuil1")
Dim LastRow As Long
LastRow = ws1.Cells(ws1.Rows.Count, "A").End(xlUp).Row
For i = 1 To LastRow
    If ws1.Cells(i, 2) = ws1.Cells(i, 5) Then 
        ws1.Cells(i, 6) = "OK"
        Else: ws1.Cells(i, 6) = "FALSE"
      End If
Next i
End Sub