How to handle change text of span

后端 未结 3 404
清酒与你
清酒与你 2021-01-03 17:56

I\'m using jQuery and I want to show some calculation in a span (called span1) and I want when text of span1 changed do some calculation on it\'s v

相关标签:
3条回答
  • 2021-01-03 18:22

    You could use the function that changes the text of span1 to change the text of the others.

    As a work around, if you really want it to have a change event, then don't asign text to span 1. Instead asign an input variable in jQuery, write a change event to it, and whever ur changing the text of span1 .. instead change the value of your input variable, thus firing change event, like so:

    var spanChange = $("<input />");
    function someFuncToCalculateAndSetTextForSpan1() {
        //  do work
        spanChange.val($newText).change();
    };
    
    $(function() {
        spanChange.change(function(e) {
            var $val = $(this).val(),
                $newVal = some*calc-$val;
            $("#span1").text($val);
            $("#spanWhatever").text($newVal);
        });
    });
    

    Though I really feel this "work-around", while useful in some aspects of creating a simple change event, is very overextended, and you'd best be making the changes to other spans at the same time you change span1.

    0 讨论(0)
  • 2021-01-03 18:35

    Span does not have 'change' event by default. But you can add this event manually.

    Listen to the change event of span.

    $("#span1").on('change',function(){
         //Do calculation and change value of other span2,span3 here
         $("#span2").text('calculated value');
    });
    

    And wherever you change the text in span1. Trigger the change event manually.

    $("#span1").text('test').trigger('change'); 
    
    0 讨论(0)
  • 2021-01-03 18:38

    Found the solution here

    Lets say you have span1 as <span id='span1'>my text</span>
    text change events can be captured with:

    $(document).ready(function(){
        $("#span1").on('DOMSubtreeModified',function(){
             // text change handler
         });
    
     });
     
    
    0 讨论(0)
提交回复
热议问题