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

时间:2010-06-11 21:15:27

标签: javascript jquery

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

<script>
    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));
</script>

在此示例中,“分子”是我在外部脚本中通过使用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;

});

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

3 个答案:

答案 0 :(得分:2)

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

<script>
function LoadMolecule(molecule) {
    var transform1 = new TransformCanvas('transform1', 200, 200, true);
    transform1.specs.bonds_useJMOLColors = true;
    //...etc...
    transform1.specs.bonds_clearOverlaps_2D = true;
    transform1.loadMolecule(readPDB(molecule));
}
</script>

则...

$(".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);    
});

答案 1 :(得分:0)

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

您必须使用脏eval(),但请注意implications

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

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

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

答案 2 :(得分:0)

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