sourcecode

jquery를 사용하여 단추를 동적으로 추가하는 방법

copyscript 2023. 2. 23. 23:01
반응형

jquery를 사용하여 단추를 동적으로 추가하는 방법

내 작업은 div에 동적으로 버튼을 추가하는 것이다.여기에 동적으로 버튼을 추가하기 위해 따르는 코드가 있지만 작동하지 않습니다. 이에 대한 해결책을 알려주세요.

<!DOCTYPE html>
    <html>
    <head>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
         <script type="text/javascript">
             function test() {
                var r = "$('<input/>').attr({
                             type: "button",
                             id: "field"
                        })";
             }
             $("body").append(r);
         </script>
    </head>
    <body>
         <button onclick="test()">Insert after</button> 
    </body>
    </html>

페이지가 로드되었지만 작동하지 않을 때 div에 버튼을 추가하는 코드

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field"

    });
    test().append("#test");    
}
</script>
</head>
<body>
<div id="test"></div>
 <button id="insertAfterBtn" onclick="test()">Insert after</button>
</body>
</html>

추가 행이 다음 중 하나에 있어야 합니다.test()기능.

편집:

다음 두 가지 버전이 있습니다.

버전 1: jQuery 리스너

$(function(){
    $('button').on('click',function(){
        var r= $('<input type="button" value="new button"/>');
        $("body").append(r);
    });
});

데모 (여기서

버전 2: 기능 포함(예시)

function createInput(){
    var $input = $('<input type="button" value="new button" />');
    $input.appendTo($("body"));
}

데모 (여기서

주의: 이것은 다음 중 하나로 실행할 수 있습니다..appendTo또는 을 사용하여.append.

플라이에 동적 버튼을 추가하는 방법

<!DOCTYPE html>
<html>
<head>
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
     <script type="text/javascript">
        function newButtonClickListener() {
                alert("Hello World");
        }
         function test() {
            var r = $('<input/>').attr({
                         type: "button",
                         id: "field",
                         value: "New Button",
                         onclick: "newButtonClickListener()"
                    });

            $("body").append(r);
         }
     </script>
</head>
<body>
     <button onclick="test()">Insert after</button><br/> 
</body>
</html>

데모 링크

$("body").append(r)스테이트먼트는 다음 범위 내에 있어야 합니다.test기능, 또한 위치가 잘못되어 있습니다."에서test방법

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

데모: 바이올린

갱신하다
이 경우 좀 더 jQuery 같은 솔루션을 사용해 보십시오.

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

데모: 플런커

이것을 시험해 보세요.

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

이거 드셔보세요

function test()
{
   $("body").append("<input type='button' id='field' />");
}

여기서 일하는 거지

새 입력을 한 번만 추가하려면 다음 코드를 사용합니다.

$(document).ready(function()
{
  $("#insertAfterBtn").one("click", function(e)
  {
    var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });

    $("body").append(r);
  });
});

[... 소스 벗겨짐...]

<body>
    <button id="insertAfterBtn">Insert after</button>
</body>

[... 소스 벗겨짐...]

w3 에디터에서 작동시키려면 아래 코드를 w3 에디터의 '소스 코드' 섹션에 복사/붙여넣은 다음 '코드 제출'을 누르십시오.

<!DOCTYPE html>
<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  </head>

  <body>
    <button id="insertAfterBtn">Insert only one button after</button>
    <div class="myClass"></div>
    <div id="myId"></div>
  </body>

<script type="text/javascript">
$(document).ready(function()
{
  // when dom is ready, call this method to add an input to 'body' tag.
  addInputTo($("body"));

  // when dom is ready, call this method to add an input to a div with class=myClass
  addInputTo($(".myClass"));

  // when dom is ready, call this method to add an input to a div with id=myId
  addInputTo($("#myId"));

  $("#insertAfterBtn").one("click", function(e)
  {
    var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });

    $("body").append(r);
  });
});

function addInputTo(container)
{
  var inputToAdd = $("<input/>", { type: "button", id: "field", value: "I was added on page load" });

  container.append(inputToAdd);
}
</script>

</html>

언급URL : https://stackoverflow.com/questions/18226598/how-to-add-a-button-dynamically-using-jquery

반응형