jQuery>在表单提交时更新内联脚本

我正在使用ChemDoodle Web Components在网页上显示分子。 基本上,我可以在我的页面中插入以下脚本,它将创建一个HTML5canvas元素来显示分子。

 var transform1 = new TransformCanvas('transform1', 200, 200, true); transform1.specs.bonds_useJMOLColors = true; transform1.specs.bonds_width_2D = 3; transform1.specs.atoms_useJMOLColors = true; transform1.specs.atoms_circles_2D = true; transform1.specs.backgroundColor = 'black'; transform1.specs.bonds_clearOverlaps_2D = true; transform1.loadMolecule(readPDB(molecule));  

在此示例中,“分子”是我通过使用jQuery.ajax()函数加载PDB文件在外部脚本中定义的变量。 这一切都很好,很好。

现在,我想在页面上包含一个表单,允许用户粘贴PDB分子定义。 提交表单后,我想用表单数据更新“分子”变量,以便ChemDoodle Web Components脚本能够运行其魔术和显示分子,该分子由粘贴到表单中的PDB定义定义。

我使用以下jQuery代码来处理表单提交。

 $(".button").click(function() { // validate and process form here //hide previous errors $('.error').hide(); //validate pdb textarea field var pdb = $("textarea#pdb").val(); if (pdb == "") { $("label#pdb_error").show(); $("textarea#pdb").focus(); return false; } molecule = pdb; }); 

此代码在表单提交时设置“分子”变量,但不会像我希望的那样将其传递回内联脚本。 我已经尝试了很多这方面的变化,但似乎无法做到正确。 关于我可能出错的地方的任何线索都将非常感激。

也许让你的内联脚本成为一个函数?

  

然后…

 $(".button").click(function() { // validate and process form here //hide previous errors $('.error').hide(); //validate pdb textarea field var pdb = $("textarea#pdb").val(); if (pdb == "") { $("label#pdb_error").show(); $("textarea#pdb").focus(); return false; } LoadMolecule(pdb); }); 

编辑:我认为我大量误解了这个问题。 我以为你有一个JavaScript代码的文本框,你需要将其解析为JavaScript才能构成你的一个molocules :)。 关于偶然的机会,我确实读了正确的问题,我会在这里留下这个答案…. 🙂

你必须使用脏eval() ,但要注意其含义

 try { eval(pdb); } catch (e) { // error; syntax error in their code. }; 

设置molecule = pdb并没有多大意义。 eval返回最后一个表达式返回的值(例如,在您的示例中返回loadMolecule )。

它之所以不起作用的原因是因为pdb只是字符串(JavaScript并不关心它是否包含有效的JavaScript;它只是一个字符串!)

你提到你正在使用表格。 如果它是真实的,你需要阻止页面提交吗? 如果是这样,我认为你需要在成功路径的某处return false ,以防止表单实际提交。