如何将多个变量从funtion传递给jquery attr [英] How to pass multiple variables from funtion to jquery attr

查看:82
本文介绍了如何将多个变量从funtion传递给jquery attr的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


此问题与如何将多个变量从函数传递到函数


所以在上面的链接中你可能已经看到了如何通过从函数到函数的变量(或多个),但如果要将它从常规js函数传递到jquery .attr()值,该怎么办? / strong>



这可能听起来很奇怪,这就是为什么我会包含一个例子。



  $(function(){function definingVars(){var Value =sucess with the value; var Id = successWithTheId; var Class = sucessWithTheClass ; return [Value,Id,Class];} $(input)。attr({// var df = definingVars();语法错误!!! value:df.Value,id:df.Id,class:df.Class})});  

 < script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< ; input type =textid =noSucessWithTheIdclass =noSucessWithTheClassvalue =没有成功的值>  



但是你可以看到应该大声说出 attr jquery函数的行来捕获<$ c中的值$ c> definingVars()被明确注释,因为这不是正确的语法。



但是你怎么能传递这些变量呢? / p>

这是我的问题

解决方案

你要做的是将多个属性传递给 .attr(),我们使用具有键/值对的对象。



所以你可以做的是从 determineVars 返回一个对象,并传递<$ c $返回的值c> definingVars 作为参数 attr()喜欢



  $(function(){function definingVars(){var Value =Sucess with the value; var Id = successWithTheId; var Class = sucessWithTheClass; return {value:Value,id:Id,class:Class}; } $(input)。attr(definingVars())});  


This question is related to How to pass multiple variables from function to function

So in the link above you might have seen how you can pass a variable(or mutiple) from function to function, but what if you want to pass it from a regular js function into the jquery .attr() value?

That might sound strange as a statement, that's why I'll include an example.

$(function() {

  function definingVars() {
    var Value = "Sucess with the value";
    var Id = successWithTheId;
    var Class = sucessWithTheClass;
    return [Value, Id, Class];
  }

  $("input").attr({
    //  var df = definingVars();  Incorrect syntax!!!
    value: df.Value,
    id: df.Id,
    class: df.Class
  })

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="noSucessWithTheId" class="noSucessWithTheClass" value="No sucess with the value">

But as you can see the line that should aloud the attr jquery function to capture the values from definingVars() is clearly commented as that is not the correct syntax.

But how can you still pass on those variables?

That is my question

解决方案

What you are trying to do is to pass multiple properties to .attr(), for which we uses an object with key/value pair.

So what you can do is to return an object from definingVars and pass the value returned by definingVars as the argument to attr() like

$(function() {

  function definingVars() {
    var Value = "Sucess with the value";
    var Id = successWithTheId;
    var Class = sucessWithTheClass;
    
    return {
      value: Value,
      id: Id,
      class: Class
    };
  }

  $("input").attr(definingVars())

});

这篇关于如何将多个变量从funtion传递给jquery attr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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