use a href as a var in a jquery function
I have a function that requires some vars being appended to a div. One of the vars is an a href link with onclick. How do I format the link to work in the var within the function? The below is not working.
What the whole purpose of this is is to
- evaluate a block of text. Count and limit the display to 200 characters
- insert an ahref link with onclick before the remainder of the text开发者_JAVA技巧
- throw a span around the remainder of the text
- after the link insert another ahref link within the span, right before the closing span tag
- and insert all of this modified content in a div
I've taken two snippets of code
1) trim text, and wrap in span jquery limit text by length
2) show on click, hide on click http://girlswhogeek.com/tutorials/2007/show-and-hide-elements-with-javascript
and am trying to mash them together to come up with what I need. Each snippet works on its own.
This is the code as I have it now:
<script type="text/javascript">
function showStuff(id) {
document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
document.getElementById(id).style.display = 'none';
}
$(function() {
var limit = 200;
var chars = $("#myDiv").text();
if (chars.length > limit) {
var visiblePart = $("<div> "+ chars.substr(0, limit-1) + "</div>");
var readMore = $(<a href="#" onclick="showStuff('answer1'); return false;">open</a>);
var hiddenPart = $("<span id='answer1' style='display: none;'> " + chars.substr(limit-1) + "</span>");
var readLess = $(<a href=\"#\" onclick=\"hideStuff('answer1'); return false;\">close</a>);
});
$("#myDiv").empty()
.append(visiblePart)
.append(readMore)
.append(hiddenPart)
.append(readLess);
}
});
If you use jQuery, then use it consistently. The biggest error you have above is that the HTML is not inside strings, hence you will get a syntax error in JavaScript.
Here is a slightly improved version:
$(function() {
var limit = 200;
var chars = $('#myDiv').text();
if (chars.length > limit) {
var visiblePart = $('<div />').text(chars.substr(0, limit-1));
var readMore = $('<a />', {
href: '#',
click: function() {
hiddenPart.show();
return false;
},
text: 'open'
});
var hiddenPart = $('<span />', {text: chars.substr(limit-1)}).hide();
var readLess = $('<a />', {
href: '#',
click: function() {
hiddenPart.hide();
return false;
},
text: 'close'
});
$('#myDiv').empty()
.append(visiblePart)
.append(readMore)
.append(hiddenPart)
.append(readLess);
}
});
It is still far from perfect but might give you a start: http://jsfiddle.net/fkling/cXw5D/
Modified Felix's version above so both links weren't showing at the same time:
http://jsfiddle.net/cXw5D/4/
EDIT:
Cleaned up syntax one last time:
http://jsfiddle.net/cXw5D/5/
精彩评论