yw173
yw173

Reputation: 477

JQuery .html can not adding variable value into a href

I want to create a list of news on my webpage. When mouse click on the content, there will be a url available. For example apple news

Here are my sample codes, my problem is: when I try to add a variable's value into the href, like href="www.search.com?keyword="+var.keyword, it will display apple news

Actually there are a 50 objects in the variable model, so it will having 50 model.link and model.keywords, please help me to change the sample code which works on w3cshools.com "try it youself". I tried 10 times by really don't know the how to fix it, thanks!

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<!-- should end this tag-->

var model=[{"link":"http://www.google.com?keyword=","keyword":"apple" "content":"This is a news"}]
<!-- miss a ";" at the end of line -->

</script>
<script>
$(document).ready(function(){
$("p").html("Click <a href=model.link+model.keyword>this link</a>");

<!--Finally this works: $("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");-->

});
</script>
</head>
<body>

<p>A content</p>

</body>
</html>

Upvotes: 0

Views: 482

Answers (4)

Brian Ogden
Brian Ogden

Reputation: 19212

This is what you need:

var model=[ { link:'http://www.google.com?keyword=', keyword: 'apple', content: 'This is a news'} ];

$.each( model, function( key, value ) {
   $('p').append('Click <a href="' + value.link+ value.keyword + '">this link</a>');
});

You need to loop through the array of objects and get values. You can use $.each to make this easy since you are using jQuery though you can just as easily do this with vanilla Javascript, I would also get in to the practice of wrapping strings in single quotes in Javascript, that way you can add double quotes in a nice readable syntax to HTML strings you will be adding to the DOM.

Note that I did not use quotes for object keywords too.

See fiddle: http://jsfiddle.net/r8MQ9/1/

Upvotes: 0

Mr.Cocococo
Mr.Cocococo

Reputation: 1451

Put the link correctly

$("p").html("Click <a href='"+model.link+model.keyword+"'>this link</a>");

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

you missed comma in your model variable::

var model=[
  {
    "link":"http://www.google.com?keyword=",
    "keyword":"apple",
    "content":"This is a news"
  }
];

And since its array of object , you need to access it like model[0].link to get first object from model array, like:

$(document).ready(function(){
    $("p").html("Click <a href='"+model[0].link+model[0].keyword+"'>this link</a>");
});

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

Quote properly:

$("p").html("Click <a href="+model.link+model.keyword+">this link</a>");

Upvotes: 1

Related Questions