I have an input box created by jquery like so:
val input = $('<input class="pick_date" ... />')
but the .html() method on input does not return the string entered inside the $. does anyone know why?
edit:
Ah, I understand the problem. Is there a way to get the html representation of the entire input box and not just the entry?
asked Sep 8, 2009 at 21:53
Nathaniel FlathNathaniel Flath
15.5k19 gold badges69 silver badges94 bronze badges
0
you are passing <input />
which is a self-closing tag.
If you were passing <input>Html here</input>
(which is valid XML but not HTML to my knowledge), you could retrieve the «Html here» part with the .html() function like so:
var input = $('<input class="pick_date">Html here</input>');
alert(input.html());
In addition to your edited question:
$('<input />').outerHtml();
this should work..
with this ofcourse (source):
(function($) {
$.fn.outerHTML = function() {
return $('<div>').append( this.eq(0).clone()).html();
};
})(jQuery)
answered Sep 8, 2009 at 21:59
RopstahRopstah
17.6k24 gold badges120 silver badges195 bronze badges
2
I think maybe you are looking for append():
$("div#form").append('<input class="pick_date" ... />');
answered Sep 8, 2009 at 21:57
pifantasticpifantastic
8616 silver badges13 bronze badges
1
Just had to deal with this problem.
If you are using ASP.NET, it could be because ASP.NET changes the id names, if you add «runat=»server».
So instead of doing this:
<td id="mytd" runat="server"></td>
$('#mytd').html()
Try doing this:
<td id="mytd" class="myclass" runat="server"></td>
$('.myclass').html()
answered Mar 17, 2016 at 16:48
live-lovelive-love
49.1k22 gold badges240 silver badges204 bronze badges
I have a table that carries out some AJAX actions, an returns an error if one is encountered.
I’m using JS to insert this error (which is a string), but because the string has HTML tags in it, it’s being appended at the end of the JS element where I wish it to be inserted, as opposed to in the middle.
var debug_error = '<span class="debug-message hidden">'+table_obj.debug_string+'</span>',
row = $(id+' .row-debug'); // id is definded
row.html(debug_error);
For example, if debug_string
was <h3>Error</h3><p>Please define an email address</p>
, my results are —
<span class="debug-message hidden"> </span>
<h3>Error</h3>
<p>Please define an email address</p>
Yet if I remove the HTML tags, an use just ErrorPlease define an email address
, it works as expected —
<span class="debug-message hidden">ErrorPlease define an email address</span>
Does any body know why this is happening? Thanks.
Bind an event handler to the «error» event, or trigger that event on an element.
Contents:
-
.on( «error» [, eventData ], handler )
- .on( «error» [, eventData ], handler )
-
.trigger( «error» )
- .trigger( «error» )
.on( «error» [, eventData ], handler )Returns: jQuery
Description: Bind an event handler to the «error» event.
-
version added: 1.7.on( «error» [, eventData ], handler )
-
«error»
The string
"error"
. -
eventData
An object containing data that will be passed to the event handler.
-
handler
A function to execute each time the event is triggered.
-
This page describes the error
event. For the .error()
method removed in jQuery 3.0, see .error()
.
The error
event is sent to elements, such as images, that are referenced by a document and loaded by the browser. It is called if the element was not loaded correctly.
For example, consider a page with a simple image element:
1 |
|
The event handler can be bound to the image:
1 2 3 4 5 |
|
If the image cannot be loaded (for example, because it is not present at the supplied URL), the alert is displayed:
Handler for `error` called.
The event handler must be attached before the browser fires the error
event, which is why the example sets the src
attribute after attaching the handler. Also, the error
event may not be correctly fired when the page is served locally; error
relies on HTTP status codes and will generally not be triggered if the URL uses the file:
protocol.
Note: A jQuery error
event handler should not be attached to the window
object. The browser fires the window
‘s error
event when a script error occurs. However, the window error
event receives different arguments and has different return value requirements than conventional event handlers. Use window.onerror
instead.
Example:
To replace all the missing images with another, you can update the src
attribute inside the error
handler. Be sure that the replacement image exists; otherwise the error
event will be triggered indefinitely.
1 2 3 4 5 6 |
|
.trigger( «error» )Returns: jQuery
Description: Trigger the «error» event on an element.
-
version added: 1.0.trigger( «error» )
-
«error»
The string
"error"
.
-
See the description for .on( "error", ... )
.
Обновлено
Вопрос:
Я пытаюсь изменить html на странице с помощью jQuery. Хотя он работает в Firefox, он не будет в хроме. Что я могу сделать, чтобы исправить это?
Например.
$('#test').html(<p>hi</p>);
изменит текст, но если бы у меня был другой html в файле, и я его переопределяю, старый текст по-прежнему отображается в хроме. Может ли это быть проблемой кеширования? Как я могу это исправить?
Лучший ответ:
Используйте,
$('#test').html("<p>hi</p>"); //.html() accepts quoted [.html("value")] value.
Я думаю, вы хотите добавить к #test
, поэтому используйте .append()
вместо .html()
.
И если вы хотите перезаписать содержимое, используйте .html()
.
$('#test').html("<p>hi</p>"); //will override content of test.
$('#test').append("<p>hi</p>"); //will append <p>hi</p> to test.
Что-то интересное для вас,
$('#test').html(value) is equivalent to $('#test').empty().append(value).
Ответ №1
Вам не хватает котировок.
$('#test').html("<p>hi</p>");
Ответ №2
html()
принимает строку. Поэтому вам нужно инкапсулировать эти символы в кавычки.
$('#test').html("<p>hi</p>");
Ответ №3
если вы хотите заменить текст своего id #test, используйте
$('#test').html("<p>hi</p>");
хочу добавить еще добавить <p>hi</p>
в использовании тестового идентификатора
$('#test').append("<p>hi</p>");
Let’s face it, nobody is perfect! Everyone makes mistakes now and then and jQuery is the same – although they have an excellent bug fixing team who are fixing up errors and enhancing jQuery around the clock errors may appear from time to time.
In light of this and the fact that I’ve been developing with jQuery for quite a while now and every now and then an error will show in the Firebug Console and “I have to Google it”. I thought I would share some of the most common jQuery errors so that when you encounter them you might have some idea of how to solve the puzzle.
Error: “jquery.1.4.2.js error “a is null””
Possible Causes
a is null
[Break On This Error] a))();else c.error("Invalid JSON: "+a)...(d)if(i)for(f in a){if(b.apply(a[f],
jquery....min.js (line 29)
I was thinking it might have something to do with this line failing because there was no matches.
$.each(rawData.match(secureQueryRegex), function(index, currentQuery)
Then, I was thinking it may have been the size of data as it was 69,443 characters long…
Possible Solutions
But I eventually found out it was bad characters inside the data string (which was grabbed directly from HTML). See cleanHTML() function to remove bad characters form HTML.
rawData = rawData.replace(/[^<>a-zA-Z 0-9]+/g,''); /* clean up for match() statement */
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: invalid object initializer”
Possible Causes
Object declaration syntax error.
$.getScript(
{
'http://www.domain.com/js/preview.js'
});
OR
$("div").css(
{
padding:'0',
margin,'4px'
});
Possible Solutions
Remove the brackets the getScript() function can be called with just the url. The same applies to any other object declaration or function call with an object that doesn’t accept one.
$.getScript('http://www.domain.com/js/preview.js');
Change the comma to a semi colon.
$("div").css(
$("div").css(
{
padding: '0',
margin: '4px'
});
Specific Versions
Seen in 1.4.2
Error: “uncaught exception: Syntax error, unrecognized expression: [object HTMLLIElement]”
Possible Causes
This seems like a jQuery selector error. It seems to appear more frequently in v1.4.2 or earlier so try updating to the latest version of jQuery.
$(this+' a').css(
var req = $("input[@name=required]").val();
Possible Solutions
Not sure but take a look at your selectors and make sure they work properly. Try including the full jQuery versions first to get better error info on what might be causing the problem.
@ is old selector syntax.
var req = $("input[name=required]").val();
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing ) after argument list”
Possible Causes
Missing off closing brackets or curly braces.
})(jQuery
Possible Solutions
})(jQuery);
Specific Versions
Seen in 1.4.2
Error: “SyntaxError: missing : after property id”
Possible Causes
This is a repeat of the object initialize error but it’s caused by Using curly brackets when they are not needed.
$.getScript(
{
'http://www.domain.com/js/preview.js', function(data, textStatus){
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
});
Possible Solutions
$.getScript('http://www.domain.com/js/preview.js', function(data, textStatus)
{
console.log(data); //data returned
console.log(textStatus); //success
console.log('Load was performed.');
}
);
Specific Versions
Seen in 1.4.2
Error: “TypeError: jsSrcRegex.exec(v) is null”
Possible Causes
Caused by double exec on same regex OR caused by invalid html “jsSrcRegex.exec(v) is null”.
console.log(jsSrcRegex.exec(v));
console.log(jsSrcRegex.exec(v)[1]);
Possible Solutions
Check the html first:
if(jsSrcRegex.exec(html)){
console.dir(jsSrcRegex.exec(html)[1]);
}
OR
Use recompile the regex:
console.log(jsSrcRegex.exec(v));
jsSrcRegex.compile();
console.log(jsSrcRegex.exec(v)[1]);
Specific Versions
n/a
Error: “XML descendants internal method called on incompatiable object”
Possible Causes
Double full stop in jQuery chain commands.
$('.'+inElem)..removeClass('mouseover').addClass('selected');
Possible Solutions
To fix simply remove the double full stop.
Specific Versions
n/a
Error: “undetermined string literal”
You may have seen this one before!
Possible Causes
Many possible causes: could be that you put code where a selector should be or multiple line strings or wrong string format (bad characters) or angle brackets etc.
Possible Solutions
See jQuery Undetermined String Literal Error for a very detailed explanation on this error!
Specific Versions
n/a
Error: “Syntax Error: Unrecognized Expression”
Possible Causes
Missing attribute name in selector.
$('input["depDate"]').val(departureDate);
Possible Solutions
Add in the name attribute (or id, class etc) into the selector.
$('input[name="depDate"]').val(departureDate);
Specific Versions
n/a
Error: “SyntaxError: syntax error”
(click image to enlarge)
Possible Causes
Well, this error is very generic and there might be a number of reasons why is happens but in this example you can clearly see it was caused by an extra “+” in the jQuery selector.
$('.itemColumn'+currentColNum+).append(v);
Possible Solutions
Unfortunately, on this one you’ve just got to carefully check through your syntax and make sure you don’t have any mistakes. Try using something like jshint or another js checker to assist.
$('.itemColumn'+currentColNum).append(v);
Specific Versions
n/a
Error: “(d || “”).split is not a function”
Possible Causes
Sorry, I found this error and took a screenshot but can’t remember how i got it! I think it might be a live image hover bug in jQuery 1.4.2 but not sure.
Here is something bug 862 similar which i found (it was logged 5 years ago aha).
Sometimes you see a similar error which reads “jquery error d is undefined” or such which I saw a few times in jQuery 1.5.
Possible Solutions
Update to latest version of jQuery.
Specific Versions
Seen in 1.4.2
Error: “Syntax error, unrecognized expression: >”
Possible Causes
if ($('#'+$form).length == 0)
{
...
}
if ($('#'+$form))
{
...
}
Possible Solutions
Don’t try to use html as a jQuery selector element.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: #[object Object]”
Possible Causes
Using an DOM element as a jQuery selector element.
$('#'+$form)
Possible Solutions
Check your jQuery selectors are correct.
Specific Versions
Seen in 1.7.1
Error: “Syntax error, unrecognized expression: name”
Possible Causes
var code = $(':input:name=["disCode"]').val();
Possible Solutions
Move square bracket before attribute name.
var code = $(':input:[name="disCode"]').val();
Specific Versions
Seen in 1.7.2
Error: “XML descendants internal method called on incompatible Object”
Possible Causes
discElem..parent().after(data.html);
Possible Solutions
discElem.parent().after(data.html);
Specific Versions
Seen in 1.7.2
Error: “SyntaxError: invalid label”
Possible Causes
Using a colon at the end of a statement.
console.log(count):
Possible Solutions
Use a semi colon instead of a colon.
console.log(count);
Specific Versions
Seen in 1.7.2
Error: “TypeError: emails.match(/@/gim) is null”
Possible Causes
Using .length function on a regular expression which has no matches.
var emails = '',
count = emails.match(/@/igm).length;
Possible Solutions
If you reference the length property after then it simply returns undefined and no error. If you use the following you will see the error: “TypeError: count is null”.
var emails = '',
count = emails.match(/@/igm),
length = count.length;
If you check the count is not null before assigning the value it does not error and will give you 0 for a no count.
var emails = '',
regex = /@/igm,
count = emails.match(regex),
count = (count) ? count.length : 0;
Specific Versions
Seen in 1.7.2
Error: Error in Actionscript. Use a try/catch block to find error.”
Possible Causes
Using a call on a Flowplayer or Flash based Object with errors.
$f('fms2').toggleFullscreen();
Possible Solutions
Try checking the initialisation code for the Flash Object.
Specific Versions
Seen in 1.7.2
After seeing all those errors, here’s something to cheer you up!
Or you can see more errors and bugs on the Official jQuery Bug Tracker.
If you find any errors please leave a comment with the error and solution and i will add it to the list!
Cheers!