$('pre').each(function(index) {
var c = $(this).attr("class");
if (!c) {
return true;
}
// Match only Javascript code snippets
if (!c.match(/brush: js; class-name: 'jsbox'/)) {
return true;
}
var code = $(this).text();
$(this).after($("<button>Run example</button>").click(function() {
run(code);
}));
I noticed if I didn't have if (!c) {
then the loop could abrubtly halt if it found a <pre>
element without a class.
I wonder how to write this more succinctly. I'm also wondering about my matching options, since I've noticed different ways people match / compare strings in Javascript and I wondered what was "de rigueur".
3 Answers 3
It looks like whatever library you're using is generating properties and sticking them inside the class
attribute, which I've never seen before and seems questionable (why can't they be attributes on the element?). Because they look generated, could you maybe end up with something like this:
<pre class="class-name: 'jsbox'; brush: js">
or this:
<pre class="brush: js; [another property]; class-name: 'jsbox'">
If so, then you may want to only look for one property (like brush: js
) to determine if you're looking at a JS code snippet.
It's fine to use String.match()
for finding a substring but realize that String.indexOf()
is preferable if you have no need for regex: https://stackoverflow.com/a/4757501/1100355
So you would end up with something like this:
var c = $(this).attr("class");
if (!c || c.indexOf('brush: js') < 0) {
return true;
}
...
Change
var code = $(this).text();
to
var code = $(this).val();
-
\$\begingroup\$ That's not the problem. The problem is that I want to compress the '!c' lines. \$\endgroup\$Kai Hendry– Kai Hendry2012年01月09日 08:08:08 +00:00Commented Jan 9, 2012 at 8:08
What about this?
$('pre').each(function(){
var $t = $(this);
// Match only Javascript code snippets
if( ( $t.attr("class") || '') .match(/brush: js; class-name: 'jsbox'/) ){
$t.after($("<button>Run example</button>").click(function(){
alert( $t.text() );
}));
}
});
-
\$\begingroup\$ I like this answer, but you should have copied in the "TidyUp" version since I find the
$t
variable name, unconventional. \$\endgroup\$Kai Hendry– Kai Hendry2012年01月11日 09:27:17 +00:00Commented Jan 11, 2012 at 9:27