簡體   English   中英

函數內部的onclick失敗

[英]onclick inside function fail

我有3個輸入和3個按鈕。 我想通過單擊按鈕來設置一個值。 在第一組中一切正常。 設置下一個輸入時,它將更改所有輸入的值。

我該如何解決?

 $(function() { $("input").on("click", function () { var here = $(this); $("div").on("click", "button", function() { here.val(this.value); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"> <input type="text"> <input type="text"> <div> <button value="a">a</button> <button value="b">b</button> <button value="c">c</button> </div> 

您不能在click函數內部作用域click函數,而只能使用兩次click和全局變量...

$(function() {
var here;
  $("input").on("click", function () {
     here = $(this);       
  });
  $("div").on("click", "button", function() {
      here.val(this.value);
  });
});

這是你想要的嗎?

 $(function() { $("input").on("click", function () { var here = $(this); $("div").on("click", "button", function() { here.val(this.value+here.val()); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"> <input type="text"> <input type="text"> <div> <button value="a">a</button> <button value="b">b</button> <button value="c">c</button> </div> 

為什么要使用外部函數?

您可以將臨時類添加到輸入中,您想要將值更改為該類。

    $("input").on("click", function () {
       $("input").removeClass('addToThis');
       $(this).addClass('addToThis');
    });

    $("div").on("click", "button", function() {
      $(".addToThis").val(this.text());
    });

最簡單的解決方案:只需將here變量放在第一單擊列表器中:

$(function() {
  var here;
  $("input").on("click", function () {
    here  = $(this);
    $("div").on("click", "button", function() {
      here.val(this.value);
    });
  });
});

您是否要將Button的值放入最后一個聚焦的INPUT中。

這可能會有所幫助。

 $(function() { var lastFocus; $('body').on('focus','input', function () { lastFocus = this; }); $("div").on("click", "button", function() { $(lastFocus).val(this.value); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"> <input type="text"> <input type="text"> <div> <button value="a">a</button> <button value="b">b</button> <button value="c">c</button> </div> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM