我在我的代码中有一个错误,但无法看到我做错了什么。jQuery split()不....分裂?
我所拥有的是Facebook的用户ID,它通过jQuery用户界面自动完成填充的一个隐藏的输入:
<input id="fbid" type="hidden" value="12345, 567890, ">
然后我有它运行时的链接被点击张贴到墙壁jQuery的功能朋友们。
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '12345678', // App ID
channelUrl : '/channel.html', // Channel File
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
oauth : true, // enable OAuth 2.0
xfbml : true // parse XFBML
});
// Additional initialization code here
FB.login(function(response)
{
if (response.authResponse)
{
$("#send-voucher").click(function() {
// Post message to friend's wall
var opts = {
message : 'This is the message',
name : 'This is the name',
link : 'http://www.opticalexpress.co.uk',
description : 'This is the description',
picture : '/voucher_valid.png'
};
var referees = $("#fbid").val();
// remove last comma and space from the end of the string
referees = $.trim(referees);
referees = referees.substring(0, referees.length - 1);
var referee = referees.split(',');
referee.each(function() {
FB.api('/'+ referee +'/feed', 'post', opts, function(response)
{
if (!response || response.error)
{
alert('Posting error occured');
}
else
{
alert('Success - Post ID: ' + response.id);
$("#send-voucher").hide();
$("#voucher-sent").fadeIn('slow');
}
});
});
});
}
else
{
alert('Not logged in');
}
}, { scope : 'publish_stream' });
};
当我点击发送优惠券,错误是从警报对话,我else
上述声明:
Posting error occured
我在另一个警报加入明白为什么这发生在循环开始后:
$.each(referee, function() {
referee = $.trim(referee);
alert(referee); // new alert for debugging
....
此警报输出令我感到惊讶,因为referee
的值为12345, 567890
(与隐藏输入相同,但尾部空格和最后一个逗号被删除)。
因此,jQuery似乎没有正确地分割它,但它运行循环正确的次数,因为警告框会弹出两次告诉我裁判然后出现错误。 (这两个警报框都显示两次,以澄清)。 Incase这是一个巧合,我试图添加更多的ID到隐藏的输入,并可以确认警报框显示的次数与id的次数相同。
所以我想知道我做了什么错误,因为循环运行正确的时间量,但逗号分隔的ID似乎根本不会被拆分。
这里有一个简单的例子,还可以'split'无关的jQuery。它是** JavaScript **的一部分''String.prototype'。 –
您引用的代码将在'referee.each'上失败。 'each'不是数组的函数,除非你添加了它。在你的较小的代码块中,显示'$ .each(refereee,function()...)'这很好,但是主代码块会失败并带有'ReferenceError'。 –
可能会从输入中删除最后一个逗号并尝试,最后的逗号会寻找额外的输入,不是它们的.. – sree