2

それぞれ異なる ID を持つ 3 つのテキストエリアを持つ単純なフォームがあります。ボタンを押して、入力しているテキストエリアのIDを返すことができるようにしたいのですが、代わりにボタンを押すと、ボタンのIDであるbutton1を受け取ります。

<!DOCTYPE html>
<html>
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
  </script>
  <script>
    function printTagName() {
      $("#p1").html($(":focus").attr("id"));
    }
  </script>
</head>
<body>
  <form>
    <textarea id="textarea1"></textarea>
    <textarea id="textarea2"></textarea>
    <textarea id="textarea3"></textarea>
  </form>
  <p id="p1"></p>
  <button type="button" id="button1" onclick="printTagName()">Press</button>
</body>
</html>

この問題を解決するにはどうすればよいですか?

4

4 に答える 4

1

ボタンをクリックすると、フォーカスがボタンに移動します。textareaがフォーカスを受け取ったときに要素を保存し、idの を出力しtextareaます。

var focusElement = {};

$("textarea").focus(function(){
   focusElement = this;
});

$("#button1").click(function(e){
    e.preventDefault();
    $("#p1").html(focusElement.id);
});

JS フィドル: http://jsfiddle.net/ZYK7f/

于 2013-10-16T09:16:17.117 に答える
1

フォーカスを持っていたものがなくなったかどうかを知る必要がない限り、これは機能します。

たとえば、ユーザーがボタンを押す前にテキストエリアではない何かをクリックし、これを知る必要がある場合、コードは非常に複雑になります。

var hadFocus;
$(function() {
  $("textarea").on("focus",function() { hadFocus=this.id; });
});
function printTagName() {
  $("#p1").html(hadFocus || "No textarea had focus");
}
于 2013-10-16T09:14:32.633 に答える
0

次を使用して、最後にフォーカスがある TextArea を保存します。

var lastFocus;
$("TextArea").focus(function () {
   lastFocus = this;
});

そして、これはprintTagName関数を呼び出します

function printTagName() {
   $("p").html(lastFocus.id);
});
于 2013-10-16T09:27:16.467 に答える