【问题标题】:Passing a Variable To A Jquery Function将变量传递给 Jquery 函数
【发布时间】:2012-03-02 13:58:30
【问题描述】:

我有一个想要对其执行相同操作的项目列表。它们都有单独的 ID,因此我希望能够将每个 ID 的名称传递给 Jquery,以便仅在该 ID 上执行操作。 例如:

<a href="#" id="1">one</a>
<a href="#" id="2">two</a>
<div id="#test1"></div>
<div id="#test2"></div>

我希望能够做这样的事情:

function doSomething(x) {
     var div=x+'div';
     $(x).click(function() { $.(div).slideDown(); });
}

有什么想法吗?

谢谢。

【问题讨论】:

  • id="#foo" 是非法的。 id 中不能有 #

标签: jquery variables iteration


【解决方案1】:
<a href="#" class="x" d="test1">one</a>
<a href="#" class="x" d="test2">two</a>
<div id="test1" class="x"></div>
<div id="test2" class="x"></div>
function doSomething(x) 
{
   $("a.x").click(function()
   { $( "div#" + $(this).attr("d") ).slideDown(); }
   );
}

【讨论】:

    【解决方案2】:

    使用onclick 属性,可以稍微简化代码:

    <a href="#" id="1" onclick="handleClick(this)">one</a>
    <a href="#" id="2" onclick="handleClick(this)">two</a>
    <div id="#test1"></div>
    <div id="#test2"></div>
    
    function handleClick(x) {
         $('#test'+ x.id).slideDown();
    }
    

    【讨论】:

      【解决方案3】:

      您可以像这样将 jQuery 元素直接传递到函数中:

      var doSomething = function(el){
          el.click(function(){ });
      };
      
      // Single element
      var $el = $('a.class');
      doSomething($el);
      
      // Multiple elements
      var $elms = $('a.class, a#id');
      doSomething($elms);
      

      【讨论】:

        【解决方案4】:

        您可以使用像这样的data 属性将数据与html 元素一起存储,并使用jQuery 的data() 方法检索它们。试试这个。

        HTML 变化

        <a href="#" data-id="1">one</a>
        <a href="#" data-id="2">two</a>
        <div id="test1"></div>
        <div id="test2"></div>
        

        使用这个js

        $('a').click(function(){
           $('#test' + $(this).data('id')).slideDown();
        });
        

        要使用 jQuery data 方法检索数据属性值,只需传递属性的后半部分。所以在这种情况下,将id 传递给data 会给我们 id 值。

        【讨论】:

          【解决方案5】:

          这是在jquery fn中传递变量的方法

              <title>Test</title>
              <script type="text/javascript">
                  $(document).ready(function() {
                      $("#but").click(function() {
                          var n = $(this).attr("n");
                          alert(n);
                      });
                  });
              </script>
          </head>
          <body>
              <a id="but" href="#" n="I Love You">Click Here</a>
          </body>
          

          【讨论】:

            猜你喜欢
            • 2011-01-18
            • 2012-06-19
            • 2014-10-31
            • 1970-01-01
            • 1970-01-01
            • 2013-01-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多