我正在使用一个简单的脚本来缩短网址并将结果插入到span标记中。
使用jquery,我将如何遍历以下列表ID并将长URL替换为缩短的URL。
<ul class="vertical-list list-parent">
<li id="license_key_0">
<div class="primary two-quarter unit-link">
<span>http://localhost:3000/projects/313f7f5586b39cd9bf7a894894564036</span>
</div>
</li>
<li id="license_key_1">
<div class="primary two-quarter unit-link">
<span>http://localhost:3000/projects/287a990d17b680fe410329cb95af89b9</span>
</div>
</li>
<li id="license_key_2">
<div class="primary two-quarter unit-link">
<span>http://localhost:3000/projects/ff381cdb94070e1903c5f6fddc31b148</span>
</div>
</li>
</ul>
jquery:
(function ($j) {
function get_short_url(long_url, login, api_key, func) {
$j.getJSON(
"http://api.bitly.com/v3/shorten?callback=?", {
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function (response) {
func(response.data.url);
});
}
var login = "my_login";
var api_key = "my_api_key";
var long_url = "m";
get_short_url(long_url, login, api_key, function (short_url) {
console.log(short_url);
});
})(jQuery);
答案 0 :(得分:0)
测试一下:
(function ($) {
function get_short_url(long_url, login, api_key, func) {
$.getJSON(
"http://api.bitly.com/v3/shorten?callback=?", {
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
function (response) {
func(response.data.url);
});
}
var login = "my_login";
var api_key = "my_api_key";
$("ul.list-parent li").each(function()
{
var long_url = $(this).find("span").text();
get_short_url(long_url, login, api_key, function (short_url) {
console.log(short_url);
});
}
);
})(jQuery);
答案 1 :(得分:0)
$j.each($j("li div.primary"), function() {
var long_url = $j(this).find("span").html();
get_short_url(long_url, login, api_key,
function(short_url) { console.log(short_url) }
);
});
答案 2 :(得分:0)
您必须将.ajax
与dataType: "jsonp"
一起使用。要进行迭代,请使用.each
,如下所示:http://jsfiddle.net/37Zv4/。
(function ($j) {
function get_short_url(long_url, login, api_key, func) {
$j.ajax({
url: "http://api.bitly.com/v3/shorten",
data: {
"format": "json",
"apiKey": api_key,
"login": login,
"longUrl": long_url
},
dataType: "jsonp",
success: function (response) {
func(response.data.url);
}
});
}
var login = "bitlyapioauthdemo";
var api_key = "R_f6397a37e765574f2e198dba5bb59522";
$(".unit-link span").each(function() {
var $this = $(this);
get_short_url($this.text(), login, api_key, function (short_url) {
$this.text(short_url);
});
});
})(jQuery);
答案 3 :(得分:0)
使用.each()
jquery函数迭代选择器:
$('ul .unit-link span').each(
function(index){
var long_url = $(this).text();
get_short_url(long_url, login, api_key, function (short_url) {
console.log(short_url);
});
});