Javascript Dynamically Add Elements & Allow Customization through a CSS File
I need to create a javascript file to be embbeded into/reference by a customer's sales webpage where it will scan the sales page and look for predefined section and insert required elements like labels and buttons. Followings are some of my code
Relevant code in my customer's sales page
<body onload="SalesPageStartup(2)">
<div id="divMyTarget1">
</div>
<div id="divMyTarget2">
</div>
Relevant code in my javascript
function SalesPageStartup(TotalSection)
{
var LDivName;
var LDivObj;
var LElement;
// find all defined divs
for (i = 1; i <= TotalSection; i++)
{
LDivName = "divMyTarget" + i;
LDivObj = document.getElementById(LDivName);
if (LDivObj)
{
// found div, generate content
// create a text to describe the label
LElement = document.createTextNode('Qu开发者_如何学编程antity: ');
LDivObj.appendChild(LElement);
// create the label to display quantity value
LElement = document.createElement("label");
LElement.setAttribute("for", "lbQuantity" + i);
LElement.setAttribute("id", "lbQuantity" + i);
LDivObj.appendChild(LElement);
// create the button to submit purchase
LElement = document.createElement("input");
LElement.setAttribute("type", "image");
LElement.setAttribute("id", "btPurchase" + i);
LElement.setAttribute("src", "img/btPurchase.jpg");
LElement.setAttribute("onclick", "DoPurchase()");
LDivObj.appendChild(LElement);
}
}
}
How to i make it so that all elements generated at SalesPageStartup can be easily customize by my customer's web designer through a css file? In future i would like to re-use my javascript for another customer too.
Please advice. Thank you!
Assuming the designer knows CSS, Use element identifiers: the class
attribute and id
attribute.
For example, when you document.getElementById(...)
so as to find the predefined section, add a class
attribute to it:
LDivObj = document.getElementById(LDivName);
LDivObj.class += " SalesPageStartupSection"; // use a better class name than "SalesPageStartup"
Likewise, you may want to consider specifying a class attribute as well as an id attribute whenever you call document.createElement(...)
:
LElement = document.createElement("label");
LElement.setAttribute("for", "lbQuantity" + i);
LElement.setAttribute("class", "lbQuantity"); // consider using a different class name
LElement.setAttribute("id", "lbQuantity" + i);
You then just have to make sure the web designer is aware of all the class names and id
attributes which are used.
Your best bet is to make use of the class attribute in CSS. The beauty of the class attribute is that with the same name you can assign in to multiple number of HTML divs, even if the div doesn't have an id. Using CSS on a particular div ID just renders it on that particular div and there is no re-usability. Seeing how you are looking to render same sort of elements with the same CSS properties, I would strongly suggest using classes.
精彩评论