所以我写了一些cookie,但我需要将信息附加到iframe的src末尾。问题是我无法弄清楚如何选择iframe,因为它没有id。
iframe看起来像这样:
<iframe src="www.mysite.com";>
我需要它看起来像:
<iframe src="www.mysite.com&cookie";>
但是我无法使用ID来选择iframe,因为我不是创建iframe的人,如果其他页面上有iframe,则需要选择它们并以相同方式更新。所以功能需要是通用的。如果你想查看我的cookie代码,我也可以告诉你。
如果这太模糊,请告诉我,我会更新它。
这是我认为我想要做的事情。
答案 0 :(得分:0)
您需要向每个iframe src附加内容吗?
var iframes = document.querySelectorAll('iframe');
for (var i = 0; i < iframes.length; i++) {
iframes[i].src += 'something';
}
答案 1 :(得分:0)
src属性是否始终相同?您可以通过以下方式选择它:
var frame = $("iframe[src='www.mysite.com']");
修改:
以下是获取和附加cookie的方法:
Document.cookie会将整个cookie作为字符串返回,我猜你可能只想从该cookie获得某个值。所以你可以这样做:
// This is just declaring a function that you can use to get cookie values.
function getCookie(cookieName) {
// If you open up your console and type in document.cookie, you will see
// that all cookie values are inside of this same string. So this
// function will allow you to extract the value you are looking for
// We start by creating a new Regular Expression object, that will
// be used to match a certain pattern of text.
var re = new RegExp('[; ]'+cookieName+'=([^\\s;]*)');
// This line actually uses our pattern, and returns the match from
// the cookie.
var sMatch = (' '+document.cookie).match(re);
// if we have a cookie name, and our regular expression found a match
// in the cookie, then return the value that was found from the match
if (cookieName && sMatch) {
return unescape(sMatch[1]);
}
// if we dont find a matching value, just return an empty string
return '';
}
允许您执行以下操作:
// Now we are actually CALLING our function, and pass in whatever we named
// our cookie value. The variable cookieValue will then hold this value.
var cookieValue = getCookie("cookieName");
// Here we are using jQuery to find the iframe element we want to manipulate
// and save reference to it in a variable called 'frame'
var frame = $("iframe[src='www.mysite.com']");
// From this element, we grab it's current src value
var currentSrc = frame.attr("src");
// here, we SET the frames src value, by setting it back to it's current src
// and tack on the cookie value
frame.attr("src", currentSrc + "&" + cookieValue);