在DOM中分配事件处理程序


Assigning Event handlers in DOM

我正在用DOM在PHP中动态创建一个元素。我成功地创建了元素,创建了属性,但我想知道我是否可以在其中分配事件处理程序。

例如,我想将onmouseover="function"分配给元素。有什么方法可以做到这一点吗?

$dom = new DOMDocument('1.0'); //Create new document with specified version number
$a = $dom->createElement('a',$row['sname']); //Create new a tag
$dom->appendChild($a); //Add the a tag to document
$class = $dom->createAttribute('class'); //Create the new attribute 'type'
$class->value = 'button';
$a->appendChild($class);
$href = $dom->createAttribute('href'); //Create the new attribute 'type'
$href->value = '#';
$a->appendChild($href);

为什么不像添加class属性一样添加事件?本质上onmouseover是另一个属性。

$dom = new DOMDocument('1.0'); //Create new document with specified version number
$a = $dom->createElement('a',$row['sname']); //Create new a tag
$dom->appendChild($a); //Add the a tag to document
$class = $dom->createAttribute('class'); //Create the new attribute 'type'
$class->value = 'button';
$a->appendChild($class);
$event = $dom->createAttribute('onmouseover'); //Create the new attribute 'type'
$event->value = 'my function';
$a->appendChild($event);
$href = $dom->createAttribute('href'); //Create the new attribute 'type'
$href->value = '#';
$a->appendChild($href);

现场演示

输出:

<a class="button" onmouseover="my function" href="#">test</a>