jquery
2016-05-15 39 views -1 likes 
-1

我有一个rss链接。 sample.rss。我用firefox打开它并打开。jquery脚本不工作:试图在现有链接后插入链接

在页面

我尝试:

$('h3>a>span').each(function() { 
    $(this).parent().after("<p>Test</p>") 
}) 

它的工作原理

但是当我尝试

$("h3>a>span").each(function(){ 
    url1 = 'https://www.google.co.in/search?q="'+this.textContent+'"' 
    console.log(url1) 
    $(this).parent().after('<p></p><a href="'+ url1 +'">other</a>') 
}) 

它说语法错误:指定了无效或非法串

控制台.log正确显示url1变量。

最新的问题。

再下面的工作

$("h3>a>span").each(function(){ 
    url1 = 'https://www.google.co.in/search?q="'+this.textContent+'"' 
    console.log(url1) 
    $(this).parent().after('<p></p><a href="#">other</a>') 
}) 
+0

url1 =“https://www.google.co.in/search?q="+this.textContent; - 使它更简单...引号是问题.... – sinisake

+0

问题是,我认为,报价(如从来没有提及);但在一个不相关的说明中,我建议不要在标题元素内创建一个段落;标题元素,正如其名称所暗示的,是用于标题,而不是内容。此外,对于涉及JavaScript和HTML的问题,我们确实需要看到(代表性样本)以减少您的问题;请:添加你的“[mcve]”代码样本,以便我们提供帮助。 –

+0

在示例网站上尝试此代码http://rss.cnn.com/rss/cnn_freevideo.rss –

回答

0

能否请您尝试以下内容:

$("h3>a>span").each(function() { 
    url1 = 'https://www.google.co.in/search?q=' + this.textContent; 
    console.log(url1); 
    $(this).parent().after('<p></p><a href="'+ url1 +'">other</a>'); 
}) 
+0

最新的差异 –

+0

使var('url1')变得简单并且放上必要的分号; – Pranab

0

在这里你去:https://jsfiddle.net/69Ljogo0/1/

我收拾了代码你。您的第一种方法几乎是正确的:

$(".item h3 a").each(function(){ 
    var url1 = 'https://www.google.co.in/search?q=' + this.textContent; 
    console.log(url1); 
    $(this).after('<p><a href="'+ url1 +'">other<a></p>'); 
}); 

从您提供的http://rss.cnn.com/rss/cnn_freevideo.rss的内容。

+0

您也可以替换连接到标题的默认链接。即:$(this).attr('src',url1); – jake

0

我无法理解造成问题的原因。我在想可能会有一些语法错误。

我终于找到了这个代码中的主要问题。

我想下面的工作赋予错误:

$("h3>a>span").each(function(){ 
    url1 = 'https://www.google.co.in/search?q="'+this.textContent+'"' 
    console.log(url1) 
    $(this).parent().after('<p></p><a href="'+ url1 +'">other</a>') 
}) 

问题与"。如果this.textContent包含空格或任何其他的东西,它会给出错误。

所以我用escape()函数,并改变了代码以下列

$("h3>a>span").each(function(){ 
     url1 = 'https://www.google.co.in/search?q='+ escape('"'+this.textContent+'"') 
     console.log(url1) 
     $(this).parent().after('<p></p><a href="'+ url1 +'">other</a>') 
    }) 

我想这对http://rss.cnn.com/rss/cnn_freevideo.rss和它的工作。

如果我转义整个网址,那么当我点击谷歌说错误页面未找到。所以我逃的url只有部分

注:为url1也不得含有&相反,它应与%26

它什么时候通过JavaScript的运行,这是不能接受的URL特殊字符来代替。

相关问题