JavaScript - 获取数组中的所有最后一项 [英] JavaScript - Get all but last item in array

查看:78
本文介绍了JavaScript - 获取数组中的所有最后一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

 function insert(){
  var loc_array = document.location.href.split('/');
  var linkElement = document.getElementById("waBackButton");
  var linkElementLink = document.getElementById("waBackButtonlnk");
  linkElement.innerHTML=loc_array[loc_array.length-2];
  linkElementLink.href = loc_array[loc_array.length];
 }

我希望linkElementLink.href抓住数组中最后一个项目以外的所有内容。现在它被打破了,它之前的项目获得了第二个到最后的项目。

I want linkElementLink.href to grab everything but the last item in the array. Right now it is broken, and the item before it gets the second-to-last item.

推荐答案

使用 pathname 优先于 href 仅检索链接的路径部分。否则,如果有?查询 #fragment 后缀,或路径为 / (无父级)

Use pathname in preference to href to retrieve only the path part of the link. Otherwise you'll get unexpected results if there is a ?query or #fragment suffix, or the path is / (no parent).

linkElementLink.href= location.pathname.split('/').slice(0, -1).join('/');

(但是,当然可以这样说:)

(But then, surely you could just say:)

linkElementLink.href= '.';

不要这样做:

linkElement.innerHTML=loc_array[loc_array.length-2];

从任意字符串设置HTML是危险的。如果您使用此文本的网址包含HTML中特殊字符,例如 <& ,则用户可以注入标记。如果您可以在网址中获得< script> (您无法使其无效,但某些浏览器可能会让您无论如何)现场脚本安全漏洞。

Setting HTML from an arbitrary string is dangerous. If the URL you took this text from contains characters that are special in HTML, like < and &, users could inject markup. If you could get <script> in the URL (which you shouldn't be able to as it's invalid, but some browser might let you anyway) you'd have cross-site-scripting security holes.

要设置元素的文本而不是HTML,请使用 document.createTextNode('string') 并将其附加到元素或分支代码以使用 innerText (IE)或 textContent (其他现代浏览器)。

To set the text of an element, instead of HTML, either use document.createTextNode('string') and append it to the element, or branch code to use innerText (IE) or textContent (other modern browsers).

这篇关于JavaScript - 获取数组中的所有最后一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆