patternjavascriptMinor
Using TAGS with <script> on your websites
Viewed 0 times
scriptyourwebsiteswithtagsusing
Problem
This function creates a series of links at a desired destination by the usage of a premade tag system.
Usage:
Result would be:
Note: each of
Usage:
createMyTAGS_DATApasses in a single line of all the links as:LinkText;LinkAddress;;
createMyTAGS_LOCATIONpasses the destination to adiv,span,... to render the result
Result would be:
LinkText1LinkText2 [...]Note: each of
tag(LinkText;LinkAddress;;) must have more than 10 characters.click here
function createMyTAGS(createMyTAGS_DATA,createMyTAGS_LOCATION){
try{ var linkTags = createMyTAGS_DATA;
var v1 = createMyTAGS_LOCATION;
while (linkTags !== '' && linkTags.indexOf(";;") > 10){
var linkNew = linkTags.slice(0, linkTags.indexOf(";;"));
var linkText = linkNew.slice(0, linkNew.indexOf(";"));
linkTags = linkTags.replace(linkNew+';;', '');
linkNew = linkNew.replace(linkText+';', '');
linkNew = ''+
linkText+' ';
document.getElementById(v1).innerHTML =
document.getElementById(v1).innerHTML + linkNew;
}
}catch(err){alert('createMyTAGS: '+err.message+
'; - statement('+createMyTAGS_DATA+','+createMyTAGS_LOCATION+')')}
}
Solution
From a once over;
becomes
My counter proposal:
- Indent your code, it will be easier to read
- Use lowerCamelCase for your names
createMyTAGS->createMyTags, though personally I would call the functioncreateLinks
- I would call
createMyTAGS_DATAsimplysfor string ordata
- I would call
createMyTAGS_LOCATIONeitheridorelementorelementID, you wont then feel the need to assign that parameter to the slightly better namedlinkTags
- For your string handling, you should read up on
.split(), it would make this so much easier
alertstatements are terrible, this function should never go wrong. Consider usingconsole.loginstead if you must.
- If you have long variables or chained variables (which you should avoid), consider
+=:
document.getElementById(v1).innerHTML = document.getElementById(v1).innerHTML + linkNew;becomes
document.getElementById(v1).innerHTML += linkNew;- Consider using
addEventListenerinstead of assigning the event listener straight into the HTML
My counter proposal:
function createLinks(data, elementId){
var element = document.getElementById(elementId),
links = data.split(';;'),
html = element.innerHTML,
linkParts, url, text;
links.forEach( function( link ){
linkParts = link.split(';');
text = linkParts[0];
url = linkParts[1];
html += ''+text+' ';
});
element.innerHTML = html;
}
click here
Context
StackExchange Code Review Q#70542, answer score: 3
Revisions (0)
No revisions yet.