4

クリックされたボタンを変更したい。初期状態では、「編集」ボタンは 1 つしかありません。クリックすると「保存」ボタンになり、その横に「キャンセル」ボタンも表示したいです。どうやってやるの?以下のコードがあります。

    <!DOCTYPE html>
    <html>
    <head>
    <script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <meta charset=utf-8 />
    <title>demo by roXon</title>
    <!--[if IE]>
      <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
    <![endif]-->
    </head>

    <body>
    <button data-text="Save">Edit</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>

<script>
$("button").click(function(){
    $(this).nextUntil('button').toggle();


    var btnText = $(this).text();
    $(this).text( $(this).data('text') );
    $(this).data('text', btnText );
});
</script>

</body>
</html>
4

2 に答える 2

3

キャンセル用の新しいボタンを追加して、必要に応じて非表示にすることができます。ここでデモをフォローできます

必要な場合のコードは次のとおりです。

<button id='EditSave' data-text="Save">Edit</button>
<button id='Cancel' data-text="Cancel" style="display:none;">Cancel</button>
    <p>Hello</p>
    <p style="display: none">Good Bye</p>​

$("#EditSave").click(function(){
    var btnText = $(this).text();
    if(btnText == 'Edit')
    {
        $(this).text('Save');
        $('#Cancel').show();
    }
    else
    {
        $(this).text('Edit');
        $('#Cancel').hide();
    }
});

$('#Cancel').click(function(){
    $(this).hide();
    $('#EditSave').text('Edit');
});
​
于 2012-07-16T19:02:12.127 に答える
2

このjsFiddle exampleのようなレイアウトと jQuery をお勧めします。

jQuery

$('.edit').click(function() {
    $(this).hide();
    $(this).siblings('.save, .cancel').show();
});
$('.cancel').click(function() {
    $(this).siblings('.edit').show();
    $(this).siblings('.save').hide();
    $(this).hide();
});
$('.save').click(function() {
    $(this).siblings('.edit').show();
    $(this).siblings('.cancel').hide();
    $(this).hide();
});

</p>

HTML

<form>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
    <div>
    <input class="edit" type="button" value="Edit" />
    <input class="save" type="button" value="Save" /> 
    <input class="cancel" type="button" value="Cancel" />
    </div>
</form>

CSS

.save, .cancel {
display:none;
}​
于 2012-07-16T20:51:08.513 に答える