【问题标题】:how to pass a returned var into another script?如何将返回的 var 传递给另一个脚本?
【发布时间】:2016-10-07 05:06:27
【问题描述】:

我正在尝试获取表单 ID 并将其动态传递到脚本中:

jQuery(document).ready(function() {
  var theFormID = jQuery(parent.document).find('.theformclass').find('input[name="form_id"]').val();
});
<script type = "text/javascript" >
  jQuery(document).ready(function() {
    jQuery('.somebutton').click(function(event) {
      jQuery(parent.document).find('#abc_HERE-IS-WHERE-I-NEED-THE-RETURNED-VALUE_number_103').fadeToggle("slow", "linear");
      jQuery('#closeShare').removeClass("hide");
      jQuery('#closeShare').addClass("show");
    });
  });

有什么帮助吗? 谢谢!

【问题讨论】:

  • 请澄清您的具体问题或添加其他详细信息以准确突出您的需求。正如目前所写的那样,很难准确地说出你在问什么。
  • 您可以将 id 传递给隐藏字段中的 html,然后从其他脚本中获取隐藏字段的值。
  • 您可以将ID存储在一个全局变量(窗口变量)中,然后再次使用

标签: jquery variables


【解决方案1】:

您可以按照以下方式动态获取表单 ID。

$(document).on('click', '#id', function(){});

使用这种方法后你的脚本一定是这样的..

<script type="text/javascript">
    jQuery(document).on("click", ".somebutton", function() {
        jQuery(parent.document).find('#abc_form_HERE-IS-WHERE-I-NEED-THE-RETURNED-VAR-VALUE_number_103').fadeToggle("slow", "linear");
    });
</script>

【讨论】:

  • 感谢您的回复 :) var 已正确返回(使用“alert”检查)。我需要的是在代码中看到“HERE-IS-WHERE-I-NEED-THE-RETURNED-VAR-VALUE”的地方动态地“粘贴”它
【解决方案2】:

你可以在这里做一些事情:

  1. 将值 theFormID 添加到全局(窗口)范围。使用 window.theFormID = 东西。请注意,混乱的全局范围不是一个好习惯。
  2. 您可以在 DOM 中添加一个隐藏元素,从中提取值,然后在需要的位置读取它。

假设你已经完成了其中任何一个,并且在 myValue 中有值:

var myValue = $('#hidden-element').val();
var selector = "#abc_form_" + myValue + "_number_103";
$(parent.document).find(selector)...

应该可以。

EDIT1:评论后

如果您的意思是说您需要在多个 formID 上构建选择器,您可以在全局范围内维护一个数组,并使用listen on it 进行任何更改。

【讨论】:

  • 感谢@Wraith,我明白了你的想法,但由于我有很多选择器,我需要填充返回的变量 - 你的建议适用于 1 个特定的选择器......无法“回显”(就像在 php 中一样)一个外部 jquery var ?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 2014-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多