developer tip

jQuery 변경 이벤트

optionbox 2020. 10. 19. 07:57
반응형

jQuery 변경 이벤트 요소-이전 값을 유지하는 방법?


오늘 아침에 검색을했는데 간단한 해결책을 찾지 못했습니다. 기본적으로 입력 요소의 변경 사항을 캡처하고 싶지만 이전 값도 알고 싶습니다.

다음은 가장 단순한 형태의 변경 이벤트와 입력 요소입니다. 분명히 $ (elem) .val ()을 사용하여 새 값을 얻을 수 있지만 이전 값을 얻기 위해 빠진 교활한 방법이 있습니까? 이 작업을 수행하는 jQuery API에 아무것도 표시되지 않지만 누군가 이미이 작업을 수행했으며 몇 가지 팁이 있습니까?

<script>
    $(document).ready(function(){
        $('#myInputElement').bind('change', function(){
            //var oldvalue = ???
            var newvalue = $(this).val();
        });
    });
</script>
<input id="myInputElement" type="text">

나는 내 자신의 솔루션을 작성하는 것에 반대하는 것이 아니라 여기서 바퀴를 다시 만들고 있지 않은지 확인하고 싶습니다.


더 나은 방법은 .data를 사용하여 이전 값을 저장하는 것입니다. 이렇게하면 멀리 떨어져 있어야하는 전역 변수를 만들 필요가 없으며 정보를 요소 내에 캡슐화 할 수 있습니다. 글로벌 변수가 나쁜 이유에 대한 실제 사례가 여기에 문서화되어 있습니다.

예 :

<script>
    //look no global needed:)

    $(document).ready(function(){
        // Get the initial value
       var $el = $('#myInputElement');
       $el.data('oldVal',  $el.val() );


       $el.change(function(){
            //store new value
            var $this = $(this);
            var newValue = $this.data('newVal', $this.val());
       })
       .focus(function(){
            // Get the value when input gains focus
            var oldValue = $(this).data('oldVal');
       });
    });
</script>
<input id="myInputElement" type="text">

이것은 트릭을 할 수 있습니다.

$(document).ready(function() {
    $("input[type=text]").change(function() {
        $(this).data("old", $(this).data("new") || "");
        $(this).data("new", $(this).val());
        console.log($(this).data("old"));
        console.log($(this).data("new"));
    });
});

여기에서 데모


$('#element').on('change', function() {
    $(this).val($(this).prop("defaultValue"));
});

포커스가 입력 필드를 벗어날 때마다 입력 필드의 값을 숨겨진 필드에 복사 할 수 있습니다 (원하는 작업을 수행해야 함). 아래 코드를 참조하십시오.

<script>
    $(document).ready(function(){
        $('#myInputElement').bind('change', function(){
            var newvalue = $(this).val();
        });
        $('#myInputElement').blur(function(){
            $('#myHiddenInput').val($(this).val());
        });
    });
</script>
<input id="myInputElement" type="text">

(예상되지 않았지만 작동해야 함).


모든 DOM 요소에는 defaultValue라는 속성이 있습니다. 데이터의 첫 번째 변경 사항을 비교하려는 경우이를 사용하여 기본값을 얻을 수 있습니다.


Russ 답변에서 그는 포커스 이벤트를 바인딩합니다. 나는 그것이 필요하다고 생각하지 않는다.

변경 이벤트에 이전 값을 저장할 수 있습니다.

<script>
    $(document).ready(function(){

        var newValue = $('#myInputElement').val();
        var oldValue;

        $('#myInputElement').change(function(){
            oldValue = newValue;
            newValue = $(this).val();
        });
    });
</script>
<input id="myInputElement" type="text">

몇 가지 포인트.

$ .fn.data 대신 $ .data 사용

// regular
$(elem).data(key,value);
// 10x faster
$.data(elem,key,value);

Then, You can get the previous value through the event object, without complicating your life:

    $('#myInputElement').change(function(event){
        var defaultValue = event.target.defaultValue;
        var newValue = event.target.value;
    });

Be warned that defaultValue is NOT the last set value. It's the value the field was initialized with. But you can use $.data to keep track of the "oldValue"

I recomend you always declare the "event" object in your event handler functions and inspect them with firebug (console.log(event)) or something. You will find a lot of useful things there that will save you from creating/accessing jquery objects (which are great, but if you can be faster...)


I created these functions based on Joey Guerra's suggestion, thank you for that. I'm elaborating a little bit, perhaps someone can use it. The first function checkDefaults() is called when an input changes, the second is called when the form is submitted using jQuery.post. div.updatesubmit is my submit button, and class 'needsupdate' is an indicator that an update is made but not yet submitted.

function checkDefaults() {
    var changed = false;
        jQuery('input').each(function(){
            if(this.defaultValue != this.value) {
                changed = true;
            }
        });
        if(changed === true) {
            jQuery('div.updatesubmit').addClass("needsupdate");
        } else {
            jQuery('div.updatesubmit').removeClass("needsupdate");
        }
}

function renewDefaults() {
        jQuery('input').each(function(){
            this.defaultValue = this.value;
        });
        jQuery('div.updatesubmit').removeClass("needsupdate");
}

I found a dirty trick but it works, you could use the hover function to get the value before change!

참고URL : https://stackoverflow.com/questions/1159046/jquery-change-event-on-an-input-element-any-way-to-retain-previous-value

반응형