JQuery如何在div

时间:2016-01-09 21:03:19

标签: jquery

我想在div中添加特定数量的跨度。我想要添加的跨度数在输入字段中输入,但是此输入可能会更改,因此我需要检查这是否已更改...

#input-width是我获得跨度数的字段 .cropper-dragger是我添加跨度的div

我有这个代码,但它总是给我加上1个跨度......我做错了什么???

$(document).ready(function(){
    var xds = setInterval(function(){ 
       $("#input-width").val(); 
    }, 100);

    for (var i = 0; i < xds; i++) {
        var $newTile = $('<span/>', {class": "dashed-x"});
        $('.cropper-dragger').append($newTile);
    }
});

4 个答案:

答案 0 :(得分:1)

您可以使用.change方法,如下所示:

  

<强>更新

     

一种全新的,不同的方法(使用.change method

     

您可以使用输入[type = number]来插入和删除元素。   好处是:

     
      
  • 开始,最小和最大值,全部作为输入属性插入。
  •   
  • 使用鼠标
  • 插入值   
  • 高级用户体验
  •   
     

Browsers that do not support input[type=number]回退到普通文本输入,为此我添加了兼容性以防止未接受的值并保持启动,最小和最大值功能。

     

WORKING FIDDLE

<强> HTML

<label for="tilesNumber">Add tiles to the black area:</label>
<input id="tilesNumber" name="tilesNumber" type="number" value="15" min="10" max="75">
<br /><br /><br />
<div id="container"></div>

<强>的jQuery

// Add-Remove Tiles.
function addTiles( start, end ) {
    for ( var i = start; i < end; i++ ) {
    $( '#container' ).append( $( '<div></div>' ).text( $( '.tile' ).length + 1 ).addClass( 'tile' ) );
  }
}
function removeTiles ( start, end ) {
    for ( var i = start; i < end; i++ ) {
        // Remove tiles backwards.
        $( '#container' ).find( '.tile:last-of-type' ).remove();
  }
}

// Handle input changes.
function handleInput( e ) {
    var // Get input's val before change.
            oldVal = parseInt( $( this ).data( 'oldVal' ) ),
            // Get input's val after change.
            newVal = parseInt( $( this ).val() ),
            // Get input's max value, defined in input attribute.
            maxVal = parseInt( $( this ).attr( 'max' ) ),
            // Get input's min value, defined in input attribute.
            minVal = parseInt( $( this ).attr( 'min' ) );

    // When input values are removed completely by "Delete" and "Backspace" buttons, this fix changes null to 0.
    if ( !newVal  ) newVal = 0;

    // Allow only use of "Arrows", "Numbers", "Numpad Numbers", " Delete" and "Backspace" buttons, if value is insserted by keyboard.
    if ( e.type == 'keyup' && !( e.which == 8 || e.which == 46 || ( e.which > 36 && e.which < 41 ) || ( e.which > 47 && e.which < 58 ) || ( e.which > 95 && e.which < 106 ) ) ){
        $( this ).val( oldVal );
        return false;
    }

    // Limitation fix ( For browsers that do not support input[type=number] and fallback to the input input[type=text] )
    if ( newVal > maxVal ) {
        newVal = maxVal;
        $( this ).val( maxVal );
    }
    if ( newVal < minVal ) {
        newVal = minVal;
    }

    // Add - Remove tiles.
    if ( newVal > oldVal) {
        //Start loop from oldVal to append tiles beggining from the last and leave previous tiles intact.
        addTiles( oldVal, newVal );
    } else {
        // Oldval = what we had, newVal = what is left, difference = how many tiles to remove ( aka repeats of removing tiles backwards loop ).
        removeTiles( 0, oldVal-newVal );
    }

    //Update oldval for later use, if input is changed again.
    $( this ).data( 'oldVal', newVal);
}

//Add tiles based on the on-load value of input ( Number can be changed by input attribute "value").
addTiles( 0, parseInt( $( '#tilesNumber' ).val() ) );

// Piece it up
$( '#tilesNumber' )
    // Store on-load value of input.
    .data( 'oldVal', $( '#tilesNumber' ).val() )
    // Give focus to input. Not necessary of course. Just for immediate keyboard insert.
    .focus()
    // We update the value on blur, so if the inserted value is lower than the min limit, it changes back to the min value. 
    .blur( function() { $( this ).val( $( this ).data( 'oldVal' ) ) } )
    // Safari fires the change event after input loses focus.
    // So we force input to lose focus so it can be updated but we focus back so user can click the input to insert from keyboard.
    .mouseup( function() { $( this ).blur().focus(); } )
    // Assign handleInput function to events
    .keyup( handleInput )
    .change( handleInput );

我保留了原来的答案,因为有一些兴趣:

$( '#input-width' ).change( function() {
    var container = $( '.cropper-dragger' ), numberOfTiles = parseInt( $( this ).val() );
    if ( $.isNumeric( numberOfTiles ) ) {
        container.children('span.dashed-x').remove();
        Math.abs( numberOfTiles );
        for ( var i = 0; i < numberOfTiles; i++ ) {
            var $newTile = $('<span/>', { class: 'dashed-x' } );
            container.append( $newTile );
        }
    } else {
        alert( 'Please enter a numeric value for number of tiles' );
    }
} );

答案 1 :(得分:1)

这也是我的解决方案:) HTML:

<input class='input' type="text" maxlength='2'/>

<div class="divtoappend">

</div>

JS:

  $(document).ready(function() {
  $(".input").keyup(function(e) {
    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
      return false;
    }
    doWork();
  });

  function doWork() {
    var number = $('.input').val();
    $('.divtoappend').html("");
    if (number) {
      for (var i = 0; i < number; i++) {
        $('.divtoappend').append("<span class='?' >Span " + i.toString() + "</span>")
      }

    }
  }
});

jsfiddle:https://jsfiddle.net/rucnmhfu/2/这里:))

答案 2 :(得分:0)

没有jQuery,只是简单的JavaScript。它很笨重但很快。

var stc = document.getElementById('struct');

stc.addEventListener('click', function(event) {

  var inw = document.getElementById('input-width');
  var val = inw.value;

  for (var i = 0; i < val; i++) {

    var cdg = document.querySelector('.cropper-dragger');
    var x = document.createElement('span');
    x.classList.add('dashed-x');
    cdg.appendChild(x);
  }
}, false);
.dashed-x {
  border: 1px dashed red;
  height: 10px;
  width: 10px;
}
.dashed-x:after {
  content: 'X';
  font-size: 1em;
  color: red;
}
.cropper-dragger {
  border: 2px solid blue;
  min-height: 10px;
  max-width: 400px;
  overflow-x: hidden;
  word-wrap: break-word;
}
#input-width {
  width: 72px;
  line-height: 2;
  border: 3px inset black;
  font-size: 1em;
  padding: 2px 5px;
  word-wrap: wrap;
}
<input id="input-width" type="number" max="9999" min="0" />
<button id="struct">CREATE</button>

<div class="cropper-dragger"></div>

答案 3 :(得分:0)

我这样做:JS Fiddle

&#13;
&#13;
$(document).ready(function() {
  $('#genBtn').on('click', function() {

    // check if the entered value is a number, else we won't execute the for-loop
    var xds = parseInt($("#input-width").val());
    if (!isNaN(xds)) {
      //if we want to reset content of .cropper-dragger div we need the below line
      $('.cropper-dragger').html('');

      // generate span.dashes-x and append them
      for (var i = 0; i < xds; i++) {
        var $newTile = '<span class="dashed-x"></span>';
        $('.cropper-dragger').append($newTile);
      }
    }
  });
});
&#13;
.dashed-x {
  background-color: orange; min-width: 20px; height: 20px; padding: 5px;
  margin: 2px; display: inline-block; border: 2px green solid;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text" id="input-width">
<button id="genBtn">Generate</button>
<hr>
<div class="cropper-dragger"></div>
&#13;
&#13;
&#13;