将数据附加到DOM元素

时间:2014-02-16 10:19:30

标签: javascript jquery html

我是jquey的新手。我面临着将数据附加到特定内部div的问题。我正在为我面临的问题编写一个演示代码,该代码与原始问题的行为相同。我必须在一个大div内进行小div,我想存储(进行一些进一步处理)并根据用户输入向小div显示一些数据。

[html code]
<div id="ctrl-1001" class="big">
   <div id="m1" class="small"></div>
   <div id="m2" class="small"></div>
</div>
<div id="input" class="control-group module">
   <label class="control-label">Module Name</label>
   <div class="controls">
      <select id="ModuleName" name="DSname" class="input-large">
        <option>TitleImage</option>
        <option>SearchBox</option>
        <option>CategoryLinks</option>
        <option selected>BannerSlides</option>
      </select>
  </div>
  <button id="sa">save</button>
</div>    
[jquery code]
 $('.small').click(function(){
    $('#input').show();
    var myId = $(this).attr("id");
    var myParentId = $(this).parents('.big').attr('id');
    var uniqueId = '#'+myParentId+' #'+myId; 
    create(uniqueId); 
 });
 function create(uniqueId){
       $('#input').show();
       $('#ModuleName').change(function(){
          var name = this.value;
          $('#sa').click(function(){
          save_name(name,uniqueId);
          });     
       });
 }
 function save_name(name,uniqueId){
    var div = $(uniqueId)[0];
    jQuery.data(div,'store',name); 
    //alert(uniqueId);
    //var val = jQuery.data(div,'store');
    $(uniqueId).text(name);
    $('#input').hide();
 } 

但问题是,当我点击第二个div来存储一些数据时,第一个div也会改变第二个div包含的值。 demo on Jsfiddle

1 个答案:

答案 0 :(得分:1)

这是因为当您第一次点击一个更改处理程序添加到具有定位#m1元素的选择时,再次单击#m2时添加了一个新的更改处理程序而不删除第一个一,所以当你点击按钮时,这两个代码都会被执行。

所以试试

$('.small').click(function () {
    var uniqueId = '#' + this.id;
    create(uniqueId);
});

function create(uniqueId) {
    $('#input').show();
    //remove previously added handlers
    //take a look at namespaced event handlers
    //also there is no need to have a change handler for the select element
    $('#sa').off('click.create').on('click.create', function () {
        var name = $('#ModuleName').val();
        save_name(name, uniqueId);
    });
}

function save_name(name, uniqueId) {
    var div = $(uniqueId);
    //you can use the .data() method instead of the static jQuery.data() method
    div.data('store', name);
    //alert(uniqueId);
    var val = div.data('store');
    $(uniqueId).text(name);
    $('#input').hide();
}

演示:Fiddle


但更多jQueryish解决方案可能看起来像

var $smalls = $('.small').click(function () {
    var uniqueId = '#' + this.id;
    $smalls.filter('.active').removeClass('active');
    $(this).addClass('active');
    $('#input').show();
});
$('#sa').on('click', function () {
    var name = $('#ModuleName').val();
    save_name(name, '.small.active');
});

function save_name(name, target) {
    var div = $(target);
    //you can use the .data() method instead of the static jQuery.data() method
    div.data('store', name);
    //alert(uniqueId);
    var val = div.data('store');
    div.text(name);
    $('#input').hide();
}

演示:Fiddle

相关问题