【问题标题】:Iterating through all Textareas with Javascript (jQuery)使用 Javascript (jQuery) 遍历所有文本区域
【发布时间】:2011-09-06 07:09:15
【问题描述】:

我想对我所有的文本区域执行一些操作,但是用$("textarea") 选择所有这些区域是不行的。这是我在伪代码中尝试做的事情:

for each textarea do
  alert(textarea.val)

就我而言,我需要在我的所有文本区域中进行 Word 替换,所以我认为使用迭代进行替换会更干净,但我不知道该怎么做。

这是我目前做的,非常繁琐:

var txtcode = $("#txt_banner1").text().replace("AFFURL",producturl);
$("#txt_banner1").text(txtcode);

var txtcode = $("#txt_banner2").text().replace("AFFURL",producturl);
$("#txt_banner2").text(txtcode);

... 不断地......

谢谢!

【问题讨论】:

    标签: jquery html textarea iteration


    【解决方案1】:
    $(function(){
        $("textarea").each(function(){
            this.value = this.value.replace("AFFURL",producturl);
        });
    });
    

    查看working demo

    【讨论】:

    • +1 for REGULAR FREAKING JAVASCRIPT 用于获取 textarea 的值,而不是 $(this).val() 或 .text() 废话。
    • 接受这个是因为常规的 javascript,这使得可读性更好。谢谢! :)
    • 我得到 ReferenceError: textarea is not defined 当我尝试从我的代码中执行 $("textarea") 时。我在我的 $(document).ready 函数中执行这个,这不正确吗?
    【解决方案2】:

    您可以使用.each 遍历所有textarea 元素并通过jQuery 对它们执行您需要的操作。

    Live Demo

    $('textarea').each(
        function(){
            alert($(this).val());
        }
    );
    

    Reference

    【讨论】:

      【解决方案3】:

      而不是使用 id 在下面做

      $("textarea").each ( function () {
      
      // whatever u want
      });
      

      【讨论】:

        【解决方案4】:

        http://jsfiddle.net/PKenB/

        //alternative 1
        $(function() {
            $('textarea').each(function() {
                alert($(this).text())
            })
        })
        
        //alternative 2 only those who has specific class  
        $(function() {
            $('textarea.myTextArea').each(function() {
                alert($(this).text())
            })
        })
        
        //alternative 3, handpicked textareas    
        $(function() {
            var handPicked = ['#2', '.myTextArea']
            for (x = 0; x < handPicked.length; x++) {
                alert($(handPicked[x]).text())
            }
        })
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-12-21
          • 1970-01-01
          • 1970-01-01
          • 2011-08-13
          • 2016-08-06
          • 2011-01-19
          相关资源
          最近更新 更多