I am using jQuery to create an anchor and bind it with JavaScript function as follow:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
do something;
}
$('#id').click
(
var content = "Hello world";
var anchor = "<a href='javascript:void(0);' onclick='test(\"" + content + "\")' >test</a>";
$('#DivToBind').prepend(anchor);
);
}
);
And the problem is: the test function always alerts "a", no matter what the value of content is. If I change onclick function test to anotherTest, nothing happens but "anotherTest is not defined" appeared in the error console
Edit
To better identify my problem, I summarise my real code as follow
$(document).ready
(
function()
{
var deleteComment = function (comment)
{
commentInfo = comment.split('_');
var postid = commentInfo[0];
var enum = commentInfo[1];
var parentid = commentInfo[2];
var user = commentInfo[3];
var author = commentInfo[4];
var date = commentInfo[5];
$.get
(
"ajaxhandle.php",
{ref: 'commentdelete', pid: postid, d: date},
function(text)
{
if (text)
{
//alert(comment);
$('#' + comment).html('');
}
else
{
alert("Something goes wrong");
}
},
'text'
);
};
var test = function(arg) {alert(arg);};
$('#postCommentButton').click
(
function ($e)
{
$e.preventDefault();
var comment = $('#postdata').val();
var data = $('form#commentContent').serialize();
//alert(data);
$.post
(
"ajaxhandle.php",
data,
function($xml)
{
$xml = $($xml);
if ($xml)
{
//alert(45);
var success = $xml.find("success").text();
if (success == 1)
{
$('#postdata').val("");
var id = $xml.find("id").text();
var reference = $xml.find("reference").text();
var parentid = $xml.find("parentid").text();
var user = $xml.find("user").text();
var content = $xml.find("content").text();
var authorID = $xml.find("authorid").text();
var authorName = $xml.find("authorname").text();
var converteddate = $xml.find("converteddate").text();
var date = $xml.find("date").text();
var avatar = $xml.find("avatar").text();
comment = id + '\_wall\_' + parentid + '\_' + user + '\_' + authorID + '\_' + date;
//alert(comment);
var class = $('#wallComments').children().attr('class');
var html = "<div class='comment' id='" + comment + "' ><div class='postAvatar'><a href='profile.php?id=" + authorID + "'><img src='photos/60x60/" + avatar +"' /></a></div><div class='postBody' ><div class='postContent'><a href='profile.php?id=" + authorID + "'>" + authorName + " </a> <span>" + content + "</span><br /><div class='timeline'>Posted " + converteddate + "<br /><a href=''>Comment</a> | <a href=''>Like</a> | <a href='javascript:void(0);' onclick='deleteComment(\"" + comment + "\")' class='commentDelete' >Delete</a></div></div></div><div style='clear:both'></div><hr class='hrBlur' /></div>";
if (class == 'noComment')
{
//alert($('#wallComments').children().text());
//alert(comment);
$('#noComment').html('');
$('#wallComments').prepend(html);
}
else if(class = 'comment')
{
//alert(comment);
$('#wallComments').prepend(html);
}
}
else
{
alert("Something goes wrong");
}
}
else
alert("Something goes wrong");
},
'xml'
);
}
);
$(".comment").find('.commentDelete').click
(
function($e)
{
$e.preventDefault();
var comment = $(this).parent().parent().parent().parent().attr('id');
deleteComment(comment);
}
);
}
);
var test=... is inside a function, it's not going to be in scope on the page when you want to call it onclick the anchor.
to make it global you can leave off the var.
you could also do something like:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
//do something;
}
$('#id').click
(
function(){
var content = "Hello world";
var anchor = "<a href='javascript:void(0);'>test</a>";
$(anchor).click(function(){ test(content); });
$('#DivToBind').prepend(anchor);
});
}
);
Your example is incomplete. The call to bind click is missing a function wrapper (so it's a syntax error and won't even parse); there is no reference to calling anotherText;, and the anchor is never actually created, only a string. So it's not really possible to fix from there.
In general avoid creating dynamic content from HTML strings. As you are not HTML-escaping content, if it contains various special characters (<"'&) your script will fail and you may have a cross-site-scripting security hole. Instead, create the anchor and then write any dynamic attributes or event handlers from script:
$(document).ready(function() {
function test(arg) {
alert(arg);
}
$('#id').click(function() {
var content= 'Hello world';
$('test').click(function(event) {
test(content);
event.preventDefault();
}).appendTo('#somewhere');
});
});
It may be preferable to use a <button> styled like a link rather than a real link, since it doesn't go anywhere. A <span> styled as a link is another possibility, preferably with a tabindex attribute to make it keyboard-accessible in that case.
I think a lot of code is missing here.
But anyway, why won't you use jQuery power to bind events?
$(document).ready(function() {
var test = function(arg) {
alert(arg);
}
var anotherTest = function(arg) {
alert("another: " + arg);
}
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a href='#'>test</a>").click(function() { test(content); });
//apply anchor to DOM
});
});
I think this is what you're looking for:
$(document).ready(function() {
var test = function(arg) {
alert(arg);
};
var anotherTest = function(arg) {
alert("we did something else:" + arg);
};
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a>test</a>").click(function(event) {
event.stopPropagation();
// test(content);
anotherTest(content);
});
$('#DivToBind').prepend(anchor);
});
}
);
This example shows good use of event.stopPropagation(). Setting an anchor's href to void() or # is often a mistake.
If you're using jQuery, I would recommend using its event handler functions like so:
$(document).ready(function() {
var test = function(arg){
alert(arg);
}
var anotherTest = function(arg){
// do something;
}
$('#id').click( function(event){
var content = "Hello world";
var anchor = $("<a>test</a>");
anchor.click(function(event){
event.preventDefault(); // instead of javascript:void();
test(content);
});
$('#DivToBind').prepend(anchor);
});
});
Related
So im having 2 functions. Problem is in styep_id variable. I know that i can just declare it in second functions, but then he wont take out data from first function. So the question is how i can use the same variable without lost data on him
P.S It shouldn't be public variable, cos it wont work. It wont hold the data.
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// Ja ir tikko kā pievienots, tad tikai izmetīsim ārā no DOM
if (!styep_id == "") {
estpt_action_links_td_jqobj = $(this).parent();
estpt_tr_jqobj = estpt_action_links_td_jqobj.parent();
stya_id = $("td.service-type-est-position-estimate-position-type-name>input.stya-id-for-styep", estpt_tr_jqobj).val();
estpt_tr_jqobj.remove();
show_stya_delete_link_if_possible(stya_id);
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"));
}
}
And
function save_configuration(){
var estpt_for_estpgt = "";
// Pārbaudam vai visām tāmes pozīciju grupām ir norādītas tāmes pozīcijas
$('.estpt-for-estpgt').each(function(){
if ($(this).find('tr.action_record_tr').size() == 0){
estpt_for_estpgt = this;
return false;
}
})
if (estpt_for_estpgt == "") {
var form = $(this).closest('form');
form.submit();
// Dzēsīsim ārā no datu bāzes
authenticity_token = $("#authenticity_token").val();
request_url = "/service_type_est_positions/" + styep_id + "/destroy_from_service_type_config";
$.post(request_url, { authenticity_token: authenticity_token}, process_service_type_est_position_delete, "json");
} else {
$.alerts.okButton = 'Labi';
jError("Vismaz vienai Tāmes pozīciju grupai nav norādīta neviena Tāmes pozīcija!", "Kļūda");
}
return false;
}
function remove_estpgt_if_has_no_estpt(estpgt_id) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
call your second function within the first and pass the variable as an argument:
function delete_estimate_position_type() {
save_configuration(styep_id)
}
function save_configuration(id){
request_url = "/service_type_est_positions/" + id + "/destroy_from_service_type_config";
}
You can use like this
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
// Get it from argument.
function remove_estpgt_if_has_no_estpt(estpgt_id,styep_id ) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
Another option is set it in hidden field.
// html
<input type = "hidden" id="styep_id_newval" value="">
// End of html
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
$("#styep_id_newval").(styep_id.val());
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
Now you can easily access code using anywhere.
$("styep_id_newval").val();
I have an html which has a form that a user could enter url if the value of the input text has www. in it i will create a variable and return it to the function then pass it to the ajax but it seems that when I check it(ajaxData var) in the console it says undefined.
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
JS:
$(function () {
function myreturnValue() {
$('#defaultForm').submit(function () {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}); //end submit
}
var ajaxData = myreturnValue();
console.log(typeof ajaxData);
var data = 'data:{' + ajaxData + '}';
});
then in the ajax I will pass the data variable. I hope my explanation is kinda clear.
Currently in your code, myreturnValue function only execute a code to register an event listener to your form, without return value (your return statement will only be triggered on submit event), so that's why it will return undefined at the first time.
Try this:
Put your url detect logic in myreturnValue function
Then put a code to prevent default submit event to be fired
Finally register a event listener for submit button.
And your original regex www. means match www with one other character, like wwww. and www0. will be valid. You may consider changing it to other regex like this one
$(function() {
function myreturnValue() {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match(w)) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}
$('#defaultForm').submit(function(e) {
e.preventDefault();
});
$('#submit').on('click', function() {
var data = 'data:{' + myreturnValue() + '}';
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
A few problems here.
Calling $('#defaultForm').submit(function () { binds a submit handler to the form. It does not submit the form nor execute the function. Please familiarize yourself with the documentation.
Your myreturnValue() doesn't return anything. You only have one top level line which is the above submit binding. Not only is it not executed, but return inside that function does not propagate up like you're expecting it to. Returning inside an event handler won't do anything in any context.
Don't declare vars inside if branches in general.
Here's a quick attempt to reorganize this code, but with this many problems the corrected code may depend on your specific needs.
(function () {
$('#defaultForm').submit(function (event) {
// prevent default form submit
event.preventDefault();
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
var value;
if (current.match('www.')) {
console.log('it already consists of www');
value = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
value = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
var data = 'data:{' + ajaxData + '}';
// Do whatever you want with data here
});
// If you want to now submit the form by hand...
$('#defaultForm').submit();
});
In your code, the myreturnValue() is only return the returnValue of the function in Submit. 'myreturnValue' function return anything because it doesn't any return value.
You executed unnecessary function to get the ajaxData.
To get the ajaxData, You only need to
$('#defaultForm').submit(function () {
contents
}
If fix the code simple...
$('#defaultForm').submit(function () {
var returnValue;
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
console.log(typeof returnValue);
var data = 'data:{' + ajaxData + '}';
console.log('data : ', data)
});
Please, Note : http://codepen.io/onyoon7/pen/mRdJJV
I'm fairly new at javascript, so this might be a silly question.
I've built a javascript button in Salesforce that does the following when clicked (http://i.stack.imgur.com/hqMhp.png)
What I'd like it to do for now is just display 4 separate alerts (I'll add in the real functions later).
Here's the code I'm using:
{!REQUIRESCRIPT("/soap/ajax/20.0/connection.js")}
var leadObj = new sforce.SObject("Lead");
var countryVal = "{!Lead.Country }";
var leadID = "{!Lead.Id}";
var ownerID = "{!Lead.OwnerId }";
function insertScript(script){
var targetNode = document.createElement('div'); // construct div for script injection
document.body.appendChild(targetNode);
try {
var el = document.createElement('script');
el.type="text/javascript";
el.innerHTML = script;
targetNode.appendChild(el);
} catch (e){
var el = document.createElement('span');
targetNode.appendChild(el);
el.innerHTML = "<br /><scr"+"ipt type='text/javascript' defer='defer'>"+script+"</script" + ">";
}
var box = new SimpleDialog("hersh"+Math.random(), true);
parent.box = box;
box.setTitle("Lead Rerouter");
box.createDialog();
box.setWidth(350);
box.setContentInnerHTML("<p align='center'><img src='/img/icon/profile24.png' style='margin:0 5px;'/><img src='/img/sales/quotes/sync_overlay_arrow.png' style='margin:5px;'/><img src='/img/icon/custom51_100/globe24.png' style='margin:0 5px;'/></p><p align='center'>Which region should this lead be routed to?</p><p align='center'><br /><button class='btn' onclick='routeAPAC(); return false;'>APAC</button><button class='btn' onclick='routeEMEA(); return false;'>EMEA</button><button class='btn' onclick='routeNA(); return false;'>NA</button><button class='btn' onclick='routeLATAM(); return false;'>LATAM</button><br><button class='btn' onclick='window.parent.box.hide(); return false;'>Cancel</button></p>");
box.setupDefaultButtons();
box.show();
}
script = "function routeAPAC(){alert (\"Lead routed to APAC!\")}";
script = "function routeEMEA(){alert (\"Lead routed to EMEA!\")}";
script = "function routeNA(){alert (\"Lead routed to NA!\")}";
script = "function routeLATAM(){alert (\"Lead routed to LATAM!\")}";
insertScript(script);
What am I doing wrong here?
Thanks!
You are over-complicating it.
document.querySelector(".generatorbutton").onclick = function() {
//add the window
}
var actionlist = {
".apa": function(){
//things to do onclick
},
".emea": function(){
//things to do onclick
},
".na": function(){
//things to do onclick
},
".latam": function(){
//things to do onclick
},
};
for(selector in actionlist) {
document.querySelector(selector).onclick = actionlist[selector];
}
Take a look at this for future references.
Hope this helps!
Due to overwriting of script variable, In your above code you can have only last one function routeLATAM will define through insertScript function
If you concatenate like below you will see all function definitions available
script = "function routeAPAC(){alert (\"Lead routed to APAC!\")}";
script += "function routeEMEA(){alert (\"Lead routed to EMEA!\")}";
script += "function routeNA(){alert (\"Lead routed to NA!\")}";
script += "function routeLATAM(){alert (\"Lead routed to LATAM!\")}";
insertScript(script);
I'm trying to search a string value in an xml file, and then append to a div if the string value is found. If not found at all, then I need to display an error text in the same div that the search term was not found.
This is basically supposed to be a search page which loads the searched items into div content.
Currently my content is loading fine. The searched term if found loads all the corresponding divs from the xml, but I've been unable to display an error if the search term was not found.
My XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<items xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<item>
<animal_id>1_1</animal_id>
<animal_title>Sparrow</animal_title>
<animal_generic>Birds 1</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>a1</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_1_Animals1.html</animal_url>
</item>
<item>
<animal_id>1_2</animal_id>
<animal_title>Crow</animal_title>
<animal_generic>Birds 2</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>b2</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_2_Animals2.html</animal_url>
</item>
<item>
<animal_id>1_3</animal_id>
<animal_title>Parrot</animal_title>
<animal_generic>Birds 3</animal_generic>
<animal_category>Birds</animal_category>
<animal_code>c3</animal_code>
<animal_img>http://i.imgur.com/R0754lr.png</animal_img>
<animal_url>1_3_Animals3.html</animal_url>
</item>
</items>
HTML
<div class="list-h">
</div>
Javascript
var s_string = 'bird';
$.ajax({
url: 'https://dl.dropboxusercontent.com/u/27854284/Stuff/Online/XML_animals.xml', // name of file you want to parse
dataType: "xml",
success: function parse(xmlResponse){
$(xmlResponse).find("item").each(function() {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name, results_string = '', error;
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if(found_string){
$('.list-h').append(results_string);
$('<div id="error_div"></div>').text("found");
}
}); //xmlResponse .each function end.
}, error: function(){console.log('Error: Animals info xml could not be loaded.');}
});
// START OF NOT FOUND SEARCH SCRIPT
$(window).load(function(){
var error_found = $('#error_div').text(); console.log(error_found);
setTimeout(function(){
if(error_found != 'found'){
var results_string = '<center>Your Search Query "<b>' + $.url().param('q').replace("%20"," ") + '" was not found!</b> Maybe you entered an invalid search query.</center>';
$('.list-h').append(results_string); }
}, 0);
});
// END OF NOT FOUND SEARCH SCRIPT
And here's the js fiddle with complete XML url: http://jsfiddle.net/mohitk117/B89Ms/
Please could someone help me out regarding this? Thanks!
Some changes may sort out your problem
Add a div in your html
<div id="error_div"></div>
Change below code
if (s_string) var s_string2 = s_string.replace("%20", " ");
//console.log(p_xml_string + s_string2);
if (p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
to
var s_string2='';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
Change found_string code like,
if (found_string) {
$('.list-h').append(results_string);
$('#error_div').text("found");
}
Optionally add css for error_div
#error_div {
color:red;
}
Live Demo
Updated success code
var found_string = false; // define found_string globally
$(xmlResponse).find("item").each(function () {
var pr_id = $(this).find("animal_id").text();
var p_title = $(this).find("animal_title").text();
var p_category = $(this).find("animal_category").text();
var p_code = $(this).find("animal_code").text();
var p_img = $(this).find("animal_img").text();
var p_url = $(this).find("animal_url").text();
var p_gen_name = $(this).find("animal_generic").text();
var p_xml_string = p_title + p_gen_name,
results_string = '',
error;
var s_string2 = '';
if (s_string) s_string2 = s_string.replace("%20", " ");
if (s_string2 && p_xml_string.toLowerCase().indexOf(s_string2) > -1) {
//console.log("FOUND : " + p_title);
results_string = '<div class="item"><div class="item-h"><a class="item-anchor" href="' + p_url + '"><div class="item-image"><img class="item-image-first" src="' + p_img + '" alt=""><div class="item-meta"><h2 class="item-title">' + p_title + '</h2><span class="item-arrow"></span></div></div></a></div></div>';
found_string = true; //// KEEP VALUES = TRUE OR FALSE IN AN ARRAY...GLOBAL ARRAY, AND THEN SEARCH THAT ARRAY FOR TRUE. IF ALL FALSE, SHOW ERROR.
}
if (found_string) { // if found then append in list
$('.list-h').append(results_string);
}
}); //xmlResponse .each function end.
if (found_string) { // if found then empty error div
$('#error_div').text("");
} else { // else show error text or not found
$('#error_div').text("not found");
}
Updated Found Demo and Not Found Demo
I'm a bit uncertain of how everything fits together because the javascript code is not self-explanatory. But, can you start by addressing this issue here...?
if(s_string)
var s_string2 = s_string.replace("%20"," ");
//console.log(p_xml_string + s_string2);
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
s_string2 variable is out of scope when you use it in this expression...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1){
What were you trying to do there? The expression above will always evaluate to false because s_string2 is undefined. In other words, whatever processing you are doing inside that if block will never be reached
Again, this variable is instantiated and disposed at the very same time...
if(s_string)
var s_string2 = s_string.replace("%20"," "); //<--- This variable's lifecycle ends here
and, this expression will always be false until you address the variable issue above...
if(p_xml_string.toLowerCase().indexOf(s_string2) > -1)
I have written my javascript too much, and now the code keeps repeating itself, whereas I lack of knowledge on how to simplify matters. I have this idea of calling variable into function, but I don't know how to call this kind of function that contains dynamic variables.
Anyone got any tips on how can I achieve this?
var container = '#content_container';
function container_load(){
var data = $(this).attr('data');
var dataObject = {command : data};
var title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
container_load();
$(container).prepend(title);
});
});
Apparently, console returned ReferenceError: Can't find variable: dataObject
There is two issue is in your code
var container = '#content_container';
var title; //title should be declare as global,same as "container" variable
function container_load(dis){
var data = dis.attr('data');
var dataObject = {command : data};
title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
}
$(function(){
$('nav').on('click', 'a', function(){
container_load($(this)); //you have to pass the current element
$(container).prepend(title);
});
});
Demo : Demo
Try this :
var container = '#content_container';
function container_load(currElementId){
var data = $("#"+currElementId).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
var title = container_load(this.id);
$(container).prepend(title);
});
});
Here your problem is that you cannot 'this' in other function for that you need to pass it from your current function.
There seems to be few mistakes in your code, The scope is wrong and the data attribute is used not correctly I presume. I suppose this is what you wanted http://jsfiddle.net/EjEqK/2/
HTML
<nav >aaa</nav>
<div id="content_container"></div>
JS
function container_load() {
var data = $(this).data("val");
var dataObject = { command: data };
$("#content_container").prepend('<h2 data-val="' + dataObject.command + '">' + dataObject.command + '</h2>');
};
$(function () { $('nav > a').on('click', container_load); });
PS: If you don't need dataObject for anything else, directly use data
I think this will help you :
function container_load(currElement){
var data = $(currElement).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
}
$(function(){
var container = '#content_container';
$('nav')on.('click', 'a', function(){
var title = container_load(this);
$(container).prepend(title);
});
});
You could do the following :
var container = '#content_container',
title; // make title global
function container_load() {
var data = $(this).attr('data');
var dataObject = { command: data };
title = '<h2 data="' + dataObject.command + '">' +
dataObject.command + '</h2>';
};
$(function () {
$('nav') on.('click', 'a', function () {
container_load.call(this); // bind this to container_load
$(container).prepend(title);
});
});
But you could do even better :
$(function () {
$('nav') on.('click', 'a', function () {
var data = $(this).attr('data');
$('#content_container').prepend(
'<h2 data="' + data + '">' + data + '</h2>'
);
});
});