简体   繁体   English

以编程方式将 javascript 值从另一个 javascript function 更改为 ZC1C425268E68385D1AB5074C17A94F1

[英]Change javascript value in one function from another javascript function programmatically

I realize this is javascript 101 and there are many questions along these lines on SO but I am extremely rusty on JS and can't seem to get this to work.我意识到这是 javascript 101 并且在这些方面有很多问题,但是我对 JS 非常生疏,似乎无法让它工作。

I am trying to change a parameter in some javascript B that calls a widget using another script A. It is important that A set the value in B before B is called so that B uses the desire value.我正在尝试更改某些 javascript B 中的参数,该参数使用另一个脚本 A 调用小部件。重要的是 A 在调用 B 之前设置 B 中的值,以便 B 使用期望值。

Here is the code I have right now:

A.
    <script type="text/javascript">
    function getName() {
    return "Raoul Walsh";
    }
    </script>
B.     
     <script type="text/javascript">
      new MyView.widget(
      {
      "name": "getName()",
      "locale": "en"
    }
      );
      </script>

The widget is not recognizing the value I want: 'Raoul Walsh' but instead recognizing the value 'getName()'.小部件没有识别出我想要的值:'Raoul Walsh',而是识别出值'getName()'。 In other words it does not realize, I'm trying to call a function.换句话说,它没有意识到,我正在尝试调用 function。

BTW, I also tried setting the value using the DOM unsuccessfully.顺便说一句,我也尝试使用 DOM 设置值失败。

How can I set the value for the widget script before it executes so that it executes using my desired value.如何在小部件脚本执行之前设置它的值,以便它使用我想要的值执行。

Thanks in advance for any suggestions在此先感谢您的任何建议

You don't need the quotes, simply call getName()您不需要引号,只需调用 getName()

<script type="text/javascript">
    function getName() {
        return "Raoul Walsh";
    }
</script>
<script type="text/javascript">
  new MyView.widget({
      "name": getName(),
      "locale": "en"
    });
</script>

In case javascript doesn't recognize the function, there may be some scoping issue going on that are hard to debug without having the full page.如果 javascript 无法识别 function,则可能存在一些在没有完整页面的情况下难以调试的范围问题。

In that case, you can fix the problem by attacching the function to the window object在这种情况下,您可以通过将 function 附加到 window object 来解决问题

<script type="text/javascript">
    window.getName = function() {
        return "Raoul Walsh";
    }
</script>
<script type="text/javascript">
  new MyView.widget({
      "name": window.getName(),
      "locale": "en"
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM