通过DOM迭代,然后连接结果文本值 [英] Iterate through the DOM and then concatenate the resulting text values

查看:294
本文介绍了通过DOM迭代,然后连接结果文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能没有很好的解释,但请与我保持联系,我还包括一个小提琴,这将有助于解释我正在努力实现的。



所以我一直在使用一个连接文本字符串(从输入框和下拉框中取出)的小型Web应用程序。这是通过点击生成按钮来实现的,后者在后台运行连接所述字符串的功能。它工作正常,但我刚刚介绍了一个addRow按钮,它使用JQuery克隆一个表单及其所有内容,然后更改行中每个元素的id(通过添加1,然后添加2,然后3 ,取决于点击+按钮的次数。



一旦有多个行,我如何迭代连接字符串的函数复制的行?我的代码可能会更好地解释这一点:



JSFiddle [这里] [1]



更新:



所以我修改了我的代码来为输入/文本框使用类,现在只是克隆了表单(因为它们有唯一的ID)在每个表单实例中都有麻烦来做某事(即连接字符串)!



这是一个更新的小提琴。实际连接字符串的代码完成了,我只是不知道如何使用 .eac

解决方案

首先我删除了您的内嵌点击和焦点处理程序。我们将用jQuery绑定它们。我还向所有输入添加了一个类,称为焦点和模糊,名为 inFieldLabel ,以方便绑定。



HTML

 < div id =placement> 
< h3>展示位置< / h3>
< form action =id =placement-formclass =placement-form>
< input type =textclass =site inFieldLabelvalue =Sitetitle =Site/>
< input type =textclass =Placedesc inFieldLabelvalue =Placement descriptiontitle =Placement description/>
< input type =textclass =Placetype inFieldLabelvalue =Placement Typetitle =Placement Type/>
< input type =textclass =size inFieldLabelvalue =Sizetitle =Size/>
< input type =textclass =pricing inFieldLabelvalue =Pricingtitle =Pricing/>
< select class =servetypetitle =服务类型>
< option> STD - 标准广告投放管理类型(即常规显示横幅)< / option>
< option> SSV - 网站提供(无广告服务器跟踪)< / option>
< option> PIX - Pixel< / option>
< option> CCD - 点击命令< / option>
< option> PCC - 像素和点击命令< / option>
< option> RMV - Rich Media视频< / option>
< option> RME - Rich Media展开< / option>
< option> RMO - Rich Media其他< / option>
< / select>
< span class =placement_span>< / span>
< / form>
< / div>
< input type =buttonvalue =+class =addRow/>
< input type =buttonid =generatevalue =生成/>

所以现在我们有clickclear和clickrecall函数定义为用作绑定的hnadlers。不确定是否在原始代码中使用,但是我添加了一个支票,以确保只有在默认值(如原始标签或空字符串)时才会调用/清除。



generatePage 函数中,您遇到的麻烦大部分是

JS

  var uniqueId = 1; 
var generatePage = function(evt){
$('。placement-form')。each(function(i,frm){
frm = $(frm); // wrap in jQuery
//我是interation counter
// frm是表单元素
var site,placement_desc,placementtype,size,pricing,servetype;
site = frm.find .site)val();
placement_desc = frm.find(。placementdesc)。val();
placementtype = frm.find(。placementtype)。
size = frm.find(。size)。val();
pricing = frm.find(。pricing)。val();
servetype = frm.find .servetype)。val();
var content ='< br />'+ site +'_'+ placement_desc +'_'+ placementtype +'_'+ size +'_'+ pricing +'_ + servetype;
frm.find('。placement_span')。html(content);
});
};

var clickclear = function(evt){
var ele = $(this);
evt.preventDefault();

if(ele.val()== ele.attr('title')){
ele.val(''); //如果值为label,然后清除用户
}

return false;
};

var clickrecall = function(evt){
var ele = $(this);
evt.preventDefault();


if(ele.val()==''){
//如果用户没有输入任何文本,然后还原为label
ele .VAL(ele.attr( '标题'));
}

return false;
};
$('。placement-form .inFieldLabel')。focus(clickclear).blur(clickrecall);

$('。addRow')。click(function(){
var formCopy = $(#placement-form)c​​lone(true);
var formCopyId ='placement-form'+ uniqueId;
formCopy.attr('id',formCopyId);
$('#placement')。append(formCopy);
uniqueId ++;
});

$('#generate')。点击(generatePage);

看到它在行动: http://jsfiddle.net/JUfgd/



然而,我不知道为什么要尝试组合这些字符串或为什么你正在使用多种形式。我假设你需要在某个地方提交所有这些数据,并且做到这一点,实际上有一个单一的形式将更有意义,他的元素具有数组符号中的 name 属性(例如 name =site [0]),那么当您提交时,您可以在服务器端循环,将所有内容分组在一起。当然克隆时可能很难处理,所以一个替代的方法是将实际输入留在表单之外,然后用js组合数据,类似于你已经在做什么 - 只会使用更有意义JSON而不是你自己的自定义字符串序列化。如果你需要更多关于这个帖子的信息一个新的问题。






我会做的是屁股一个唯一的id到形式或添加包装容器到具有唯一的id的表单,那么我将使用类而不是Id的输入/控件。这样,您可以克隆表单或其容器和所有子项,然后jsut更改顶级元素上的一个id。然后,您可以使用一个选择器,如 $(yourUniqueId .theInputClass),这样可以轻松管理。



那么你可以迭代每个表单...为了我可能会添加一个类到表单太jsut,以防万一有其他非相关的表单在同一页面,所以它将是这样的:

  $('。placementForm')。each(function(i,formEle){
// do form to the form
} );


this is probably not explained very well but please bear with me, I've also included a fiddle which will help explain what I'm trying to achieve.

so I've been working on a little web app that concatenates strings of text (taken from input boxes and drop down boxes). This is achieved by hitting a "generate" button, which in the background runs the functions to concatenate said strings. It was working fine but I have just recently introduced an "addRow" button, which using JQuery clones one of the forms and all its contents and then changes the id for each element in the row (by adding a 1, then 2, then 3, depending on the number of times the '+' button is clicked.

Once there is more than one row, how can I iterate through the function that concatenates the string for the row that is replicated? My code will probably explain this better:

JSFiddle [here][1]

UPDATE:

So I've amended my code to use classes for the inputs/text boxes and now just cloned the forms (as they have a unique ID). I'm having trouble iterating through each form instance to do "something" (i.e. concatenate the strings)!

Here's an updated fiddle. The code to actually concatenate the strings is done, I just don't know how to use the .each() function in JQuery properly!

解决方案

First i removed your inline click and focus handlers... we will bind them with jQuery instead. I also added a class to all the inputs you would call the focus and blur on called inFieldLabel to facilitate easy binding.

HTML

<div id="placement">
    <h3>Placement</h3>
    <form action="" id="placement-form" class="placement-form">
      <input type="text" class="site inFieldLabel" value="Site" title="Site" />
      <input type="text" class="placementdesc inFieldLabel" value="Placement description" title="Placement description" />
      <input type="text" class="placementtype inFieldLabel" value="Placement Type" title="Placement Type" />
      <input type="text" class="size inFieldLabel" value="Size" title="Size" />
      <input type="text" class="pricing inFieldLabel" value="Pricing" title="Pricing" />
      <select class="servetype" title="Serve Type">
        <option>STD – Standard trafficking type (ie, regular display banners)</option>
        <option>SSV – Site-served (no ad server tracking)</option>
        <option>PIX – Pixel</option>
        <option>CCD – Click command</option>
        <option>PCC – Pixel and Click command</option>
        <option>RMV – Rich Media Video</option>
        <option>RME – Rich Media Expand</option>
        <option>RMO – Rich Media Other</option>
      </select>
      <span class="placement_span"></span>
    </form>   
</div>
<input type="button" value="+" class="addRow" />
<input type="button" id="generate" value="Generate" />

So now we have the clickclear and clickrecall functions defined to use as hnadlers for binding. Not sure if you had it in your original code but i added a check to make sure it only recalls/clears if the values are the defaults (eg. the orig. label or an empty string).

The bulk of what ou were having trouble with is in the generatePage function.

JS

  var uniqueId = 1;
  var generatePage = function(evt){
    $('.placement-form').each(function(i, frm){
      frm = $(frm); // wrap in jQuery
      // i is the interation counter
      // frm is the form element
      var site, placement_desc, placementtype, size, pricing, servetype;    
      site = frm.find(".site").val();
      placement_desc = frm.find(".placementdesc").val();
      placementtype = frm.find(".placementtype").val();
      size = frm.find(".size").val();
      pricing = frm.find(".pricing").val();
      servetype = frm.find(".servetype").val();
      var content = '<br />'+site+'_'+placement_desc+'_'+placementtype+'_'+size+'_'+pricing+'_'+servetype;
      frm.find('.placement_span').html(content);
    });
  };

  var clickclear = function (evt){
    var ele = $(this);
    evt.preventDefault();

    if(ele.val() == ele.attr('title')){
      ele.val(''); // if the value is a "label" then clear it for the user
    }

    return false;
  };

  var clickrecall = function(evt) {
    var ele = $(this);
    evt.preventDefault();


    if(ele.val() == '') {
      // if the user hasnt entered any text then revert to the "label"
      ele.val(ele.attr('title'));
    }

    return false;
  };
  $('.placement-form .inFieldLabel').focus(clickclear).blur(clickrecall);

  $('.addRow').click(function() {
      var formCopy = $("#placement-form").clone(true);
      var formCopyId = 'placement-form'+uniqueId;
      formCopy.attr('id',formCopyId);
      $('#placement').append(formCopy);
      uniqueId++;
  });

  $('#generate').click(generatePage);

See it in action: http://jsfiddle.net/JUfgd/

However, im not sure why you are trying to combine these strings or why you are using multiple forms. I assume you need to submit all this data somewhere at some point and to do that it would make more sense to actually have a single form witht he elements having name attributes in array notation (eg. name="site[0]") then when you submit you can loop through on the server side with everything grouped together. Of course that can be hard to deal with when cloning so an alternate approach would be to leave the actual inputs outside of the form, and then assemble the data with js, similar to how youre already doing - only it would make more sense to use JSON for this instead of your own custom string serialization. If you need more info on any of this post a new question.


Well what i would do is assing a unique id to the form or add a wrapper container to the form that has a unique id, then i would use classes instead of Id's for the inputs/controls. This way you can clone the form or its container and all the children then jsut change the one id on that top level element. Then you can use a selector like $(yourUniqueId .theInputClass) which makes it a lot easier to manage.

Then you can just iterate over each form... for eas i would probably add a class to the form too jsut in case there are other non related forms on the same page so it would be something like:

$('.placementForm').each(function(i, formEle){
   // do stuff to the form
});

这篇关于通过DOM迭代,然后连接结果文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆