Я создал собственное решение для преобразования int в шестнадцатеричную строку и обратно, прежде чем нашел этот ответ. Неудивительно, что это значительно быстрее, чем решение .net, поскольку накладные расходы меньше.
/// <summary>
/// Convert an integer to a string of hexidecimal numbers.
/// </summary>
/// <param name="n">The int to convert to Hex representation</param>
/// <param name="len">number of digits in the hex string. Pads with leading zeros.</param>
/// <returns></returns>
private static String IntToHexString(int n, int len)
{
char[] ch = new char[len--];
for (int i = len; i >= 0; i--)
{
ch[len - i] = ByteToHexChar((byte)((uint)(n >> 4 * i) & 15));
}
return new String(ch);
}
/// <summary>
/// Convert a byte to a hexidecimal char
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
private static char ByteToHexChar(byte b)
{
if (b < 0 || b > 15)
throw new Exception("IntToHexChar: input out of range for Hex value");
return b < 10 ? (char)(b + 48) : (char)(b + 55);
}
/// <summary>
/// Convert a hexidecimal string to an base 10 integer
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static int HexStringToInt(String str)
{
int value = 0;
for (int i = 0; i < str.Length; i++)
{
value += HexCharToInt(str[i]) << ((str.Length - 1 - i) * 4);
}
return value;
}
/// <summary>
/// Convert a hex char to it an integer.
/// </summary>
/// <param name="ch"></param>
/// <returns></returns>
private static int HexCharToInt(char ch)
{
if (ch < 48 || (ch > 57 && ch < 65) || ch > 70)
throw new Exception("HexCharToInt: input out of range for Hex value");
return (ch < 58) ? ch - 48 : ch - 55;
}
Код синхронизации:
static void Main(string[] args)
{
int num = 3500;
long start = System.Diagnostics.Stopwatch.GetTimestamp();
for (int i = 0; i < 2000000; i++)
if (num != HexStringToInt(IntToHexString(num, 3)))
Console.WriteLine(num + " = " + HexStringToInt(IntToHexString(num, 3)));
long end = System.Diagnostics.Stopwatch.GetTimestamp();
Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
for (int i = 0; i < 2000000; i++)
if (num != Convert.ToInt32(num.ToString("X3"), 16))
Console.WriteLine(i);
end = System.Diagnostics.Stopwatch.GetTimestamp();
Console.WriteLine(((double)end - (double)start)/(double)System.Diagnostics.Stopwatch.Frequency);
Console.ReadLine();
}
Результаты:
Digits : MyCode : .Net
1 : 0.21 : 0.45
2 : 0.31 : 0.56
4 : 0.51 : 0.78
6 : 0.70 : 1.02
8 : 0.90 : 1.25
Или быстрый пример, который запускается в консоли на этой странице:
var startNode = jQuery("li.related-site").get(0); // quick jQ to get a testable node.
var spanLess = [];
var child = startNode.firstChild;
while(child){
if(child.nodeType == 1){
var anySpans = child.getElementsByTagName('span');
if(!anySpans.length) spanLess.push(child);
}
child = child.nextSibling;
}
spanLess;
Исходя из вашего комментария, что вы пытаетесь извлечь значения для использования с tablesorter, вы также можете найти полезную функцию для извлечения текстовых значений из узла независимо от разметки:
function extractText(node){
if(node.nodeType == 3) return node.nodeValue.trim();
if(node.nodeType == 1){
var buf = [];
var child = node.firstChild;
while(child){
var val = extractText(child);
if(val) buf.push(val);
child = child.nextSibling;
}
return buf.join(' ');
}
return '';
}
Попробуйте querySelectorAll
var notSpans = document.getElementsByTagName('div')[0].querySelectorAll(':not(span)');
for (var i = 0; i < notSpans.length; i++) {
notSpans[i].style.color = 'green';
}
<div>
<p>not a span</p>
<span>a span</span>
</div>
Благодаря bknights я смог изменить свой ответ на работу для моих нужд.
Мое полное fuction выглядит следующим образом:
var myTextExtraction = function (node) {
//console.log(node);
var child = node.firstChild;
while (child) {
if (node.getElementsByTagName('span').length) {
childValue = child.nextSibling.innerHTML;
console.log(childValue);
}
else {
childValue = child.nodeValue
console.log(childValue);
}
return childValue;
}
}
Затем я создаю node
с плагином tablesorter:
// Load the table sorter
$(".table").tablesorter(
{
textExtraction: myTextExtraction
}
);
Просматривает и выводит текст внутри <td><span>mytext</span></td>
, а также текст в <td>myothertext<td>
. Я использую это для плагина jquery TableSorter для работы со сложными данными внутри <td>
s
var startNode...
, потому что ваш образец показал, что у вас уже есть узел для работы. Если вы просто пытаетесь легко протестировать узел, вам уже нужно посмотреть, есть ли у него какие-либо промежутки, просто сделайтеif(!node.getElementsByTagName('span').length){ ... process the node }
– bknights 23 October 2015 в 21:40if(!node.querySelectorAll('span.interest').length){ ... process the node }
– bknights 23 October 2015 в 21:43