2009-10-30 64 views

回答

0

加斜杠:

\"" + titleArray[x] + "\" 
0

试试这个逃跑的属性引号,从而给你像你在你的例子中显示的单引号。

html += "<option value=\"javascript:clientGalleryLink('" + titleArray[x] + "')\">" + titleArray[x] + "</option>"; 
1
<a href='javascript:clientGalleryLink("Business")'>Link</a> 
html += "<option value='javascript:clientGalleryLink(\"" + titleArray[x] + "\")'>" + titleArray[x] + "</option>"; 

能否请您试试这个。

谢谢。

0

这样逃跑的问题是为什么最好避免在字符串中动态创建JavaScript-in-HTML。也不应该使用javascript:伪URL方案。

相反,考虑一个“不显眼的脚本”的方法:移动数据进行嵌入的JS串并进入正常属性,如class或,如果链路对应于页面上的特定元件,所述href本身:

<a class="gallerylink" href="#Business">Link</a> 

for (var i= document.links.length; i-->0;) { 
    if (document.links[i].className==='gallerylink') { 
     document.links[i].onclick= function() { 
      clientGalleryLink(this.hash.substring(1)); 
      return false; 
     }; 
    } 
} 

第二个例子:

html += "<option value='javascript:clientGalleryLink(" + titleArray[x] + ")'>" + titleArray[x] + "</option>"; 

仅仅是一个混乱。除了缺少引用titleArray值的\',以及titleArray上缺少HTML转义或JS字符串字面转义(因此如果标题中有'"<&个字符,则会出现问题)。

当您选择该选项时,您是否希望执行脚本,因为您已将它放入value?它不会。

更好地使用DOM对象,而不是试图在HTML内部的JavaScript内部插入JavaScript。例如,如果你正在寻找一个选择框每一个所选择的选项改变时调用clientGalleryLink

<div id="PlaceWhereYouWantToPutTheSelectBox"></div> 

<script type="text/javascript"> 
    var s= document.createElement('select'); 
    for (var i= 0; i<titleArray.length; i++) { 
     s.options[i]= new Option(titleArray[i], titleArray[i]); 
    } 
    s.onchange= function() { 
     clientGalleryLink(this.options[this.selectedIndex].value); 
    }; 
    document.getElementById('PlaceWhereYouWantToPutTheSelectBox').appendChild(s); 
</script> 

没有丑陋的逃避必要的,没有跨站点脚本安全漏洞。