在Javascript中添加href标签

时间:2018-12-27 18:03:55

标签: javascript jquery href

我正在基于此进行测验:

https://jsfiddle.net/thebobbyblack/xgf9k2hw/

我不知道如何在测验的“正确”响应字符串中添加链接

理想情况下,对正确答案的回答将超出文本的一部分,但我也将选择一个单独的文本。问题答案下方的一行。

对于后者,我已经尝试过:

问题:

var quiz = [
{
             "question"      :   "Q1: How many locations in Syria does the UN classify as besieged?",
        "image"         :   "",
        "choices"       :   [
                                "Zero",
                                "One",
                                "Four",
                                "Nine"
                            ],
        "correct"       :   "Zero",
        "explanation"   :   "The UN used to classify nine locations and more than 417,000 people as living under siege, but all these places, including formerly rebel-held Eastern Ghouta, have now either been evacuated or retaken by the Syrian government.",
 "link" : "http://www.hamsterdance.com",
 }

但是此代码无济于事:

if(quiz[currentquestion].hasOwnProperty('link') && quiz[currentquestion]['link'] != ""){
            if($('#question-image').length == 0){
                $(document.createElement('a'))
                    .addClass('question-image')
                    .attr('id', 'question-image')
                    .attr('src', quiz[currentquestion]['link'])
                    .attr('alt', htmlEncode(quiz[currentquestion]['question']))
                    .insertAfter('#question');
            } else {
                $('#question-image')
                    .attr('href', quiz[currentquestion]['link'])
                    .attr('alt', htmlEncode(quiz[currentquestion]['question']));
            }
        } else {
            $('#question-image').remove();
        }

我找到了行之有效的东西!现在,我只是想不通如何将数组中的项目传递为目标URL。此代码使我可以从数组中进行选择以创建链接文本。

$('<a>').addClass('linktext').attr('id','link').html('').text(quiz[currentquestion]['link']).insertAfter('#explanation'); 

我应该在jquery文档中搜索什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

解决了!谢谢您的帮助!

$('<a>').addClass('linktext').attr('id','linktext').attr('href',(quiz[currentquestion]['linkurl'])).html('').text(quiz[currentquestion]['link']).insertAfter('#explanation');   

将“ linkurl”添加到我的数组中。 Fiddle here,这个堆栈交换问题也确实有所帮助:How do I create a link using javascript?

再次感谢