从上面的元素中获取价值

时间:2019-05-14 16:02:11

标签: javascript jquery html

我目前正在使用JQuery,我有一个简单的问题。如何从下面的p标签获取信息?

HTML:

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>
    <p> Hello there </p>
    <p onclick="myFunction()"> Hello </p>
</body>

JS:

function myFunction() {
  var result = $(this).prev('p');
  alert(result)
}

但是我得到

[object Object]

希望有人可以帮助我。预先感谢

4 个答案:

答案 0 :(得分:2)

onclick属性调用函数时,this未设置为目标元素。您需要为函数指定一个参数,并显式传递this

function myFunction(el) {
  var result = $(el).prev('p');
  alert(result.text());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p> Hello there </p>
<p onclick="myFunction(this)"> Hello </p>

答案 1 :(得分:1)

当前代码中的问题是,this中的myFunction()并未引用单击的元素,因为您为处理程序附加了on*事件属性。

要解决此问题并改善逻辑,请使用不显眼的事件处理程序。由于您已经在页面上添加了对jQuery的引用,因此可以使用click(),如下所示:

$(function() {
  $('.foo').click(function() {
    var result = $(this).prev('p').text();
    console.log(result)
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Hello there</p>
<p class="foo">Hello</p>

请注意,我在示例中显示了text()属性,因为它比显示带有其所有属性的整个对象要简洁得多。另外,请始终使用console.log()进行调试,而不要使用alert()进行调试,因为后者会强制使用会掩盖问题的数据类型。这也是令人讨厌的模态。

答案 2 :(得分:0)

您可以在=INDIRECT("'S\My\Question\Is[" & A1 & ".xlxs]Sheet2'!B1") 中传递<?php if (!defined('_PS_VERSION_')) exit; class BlockRealization extends Module { protected $_html = ''; public function __construct() { $this->name = 'blockrealization'; $this->tab = 'front_office_features'; $this->version = '1.0.0'; $this->author = 'XXX'; $this->need_instance = 0; $this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_); $this->bootstrap = true; parent::__construct(); $this->displayName = $this->l('Module realization'); $this->description = $this->l('Display realization on homepage.'); $this->confirmUninstall = $this->l('Are you sure you want to uninstall?'); } public function install() { if (!parent::install() || !$this->registerHook('displayHeader') || !$this->registerHook('home') || !$this->createTables() ) return false; return true; } public function uninstall() { if (!parent::uninstall() || !$this->removeTable()) return false; return true; } protected function createTables() { /* Realization */ $res = (bool)Db::getInstance()->execute(' CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'realization` ( `id_realization_slides` int(10) unsigned NOT NULL AUTO_INCREMENT, `image_realization` varchar(255) NOT NULL, `position` int(10) unsigned NOT NULL, PRIMARY KEY (`id_realization_slides`, `image_realization`) ) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8; '); return $res; } protected function removeTable() { if (!Db::getInstance()->Execute('DROP TABLE `'. _DB_PREFIX_ . 'realization`')) return false; return true; } public function getContent() { $output = null; if (Tools::isSubmit('submit'.$this->name)) { $errors = ''; if ($_FILES) { $helper = new HelperImageUploader('realization_img'); $files = $helper->process(); if ($files) { foreach ($files as $file) { if (isset($file['save_path'])) { if (!ImageManager::checkImageMemoryLimit($file['save_path'])) $errors = Tools::displayError('Limit'); if (!$errors) { if (!ImageManager::resize($file['save_path'], dirname(__FILE__) . '/img/' . $file['name'])) $errors = Tools::displayError('error'); else { $previous_file = Configuration::get('realization_img'); $file_path = dirname(__FILE__) . '/img/' . $previous_file; if (file_exists($file_path)) unlink($file_path); $realization['image_realization'] = $file['name']; $realization['position'] = count($this->getAll()); if (!Db::getInstance()->insert('realization', $realization)) $errors = Tools::displayError('error'); } } unlink($file['save_path']); } } } } if ($errors) $output .= $this->displayError($errors); else $output .= $this->displayConfirmation($this->l('Settings updated')); } $output .= $this->generateList(); $output .= $this->displayForm(); return $output; } public function displayForm() { // Init Fields form array $fields_form[0]['form'] = array( 'legend' => array( 'title' => $this->l('Add the realization'), ), 'input' => array( array( 'type' => 'file', 'label' => $this->l('Image:'), 'name' => 'realization_img', 'hint' => $this->l('Upload image for contact:'), ) ), 'submit' => array( 'title' => $this->l('Save'), 'class' => 'btn btn-default pull-right' ) ); $helper = new HelperForm(); // Module, token and currentIndex $helper->module = $this; $helper->name_controller = $this->name; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; // Title and toolbar $helper->title = $this->displayName; $helper->show_toolbar = true; // false -> remove toolbar $helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen. $helper->submit_action = 'submit'.$this->name; $helper->toolbar_btn = array( 'save' => array( 'desc' => $this->l('Save'), 'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name. '&token='.Tools::getAdminTokenLite('AdminModules'), ), 'back' => array( 'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'), 'desc' => $this->l('Back to list') ) ); // Load current value $helper->tpl_vars = array( 'fields_value' => array( 'realization_img' => Configuration::get('realization_img') ) ); return $helper->generateForm($fields_form); } public function generateList() { $content = $this->getAll(); $fields_list = array( 'id_realization_slides' => array( 'title' => 'ID', 'align' => 'center', 'class' => 'fixed-width-xs', ), 'image_realization' => array( 'title' => $this->l('Image'), 'orderby' => false, 'search' => false ), 'position' => array( 'title' => $this->l('Position'), 'position' => 'position' , 'orderby' => false, 'search' => false ), ); $helper = new HelperList(); $helper->shopLinkType = ''; $helper->actions = array('edit', 'delete'); $helper->module = $this; $helper->listTotal = count($content); $helper->identifier = 'id_realization_slides'; $helper->title = $this->l('Realizations'); $helper->table = $this->name; $helper->imageType = 'jpg'; $helper->orderBy = 'position'; $helper->orderWay = 'asc'; $helper->position_identifier = 'id_realization_slides'; $helper->token = Tools::getAdminTokenLite('AdminModules'); $helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name; return $helper->generateList($content, $fields_list); } public function getAll() { return Db::getInstance()->ExecuteS(' SELECT * FROM '._DB_PREFIX_.'realization '); } public function ajaxProcessUpdatePositions() { $way = (int)Tools::getValue('way'); $id_quicklinks = (int)Tools::getValue('id'); $positions = Tools::getValue('realization_slides'); if (is_array($positions)) foreach ($positions as $position => $value) { $pos = explode('_', $value); if (isset($pos[2]) && (int)$pos[2] === $id_velcroquicklinks) { if (isset($position) && $this->updatePosition($way, $position, $id_quicklinks)) echo 'ok position '.(int)$position.' for id '.(int)$pos[1].'\r\n'; else echo '{"hasError" : true, "errors" : "Can not update id '.(int)$id_quicklinks.' to position '.(int)$position.' "}'; break; } } } public function updatePosition($way, $position, $id) { if (!$res = Db::getInstance()->executeS(' SELECT `id_realization_slides`, `position` FROM `'._DB_PREFIX_.'realization` ORDER BY `position` ASC' )) return false; foreach ($res as $quicklinks) if ((int)$quicklinks['id_realization_slides'] == (int)$id) $moved_quicklinks = $quicklinks; if (!isset($moved_quicklinks) || !isset($position)) return false; return (Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'realization` SET `position`= `position` '.($way ? '- 1' : '+ 1').' WHERE `position` '.($way ? '> '.(int)$moved_quicklinks['position'].' AND `position` <= '.(int)$position : '< '.(int)$moved_quicklinks['position'].' AND `position` >= '.(int)$position.' ')) && Db::getInstance()->execute(' UPDATE `'._DB_PREFIX_.'realization` SET `position` = '.(int)$position.' WHERE `id_realization_slides` = '.(int)$moved_quicklinks['id_quicklinks'])); } public function hookHome($params) { return $this->display(__FILE__, "views/templates/hook/realization.tpl"); } 并找到其this

HTML

onclick

Javascript

prev()

答案 3 :(得分:0)

function myFunction(id) {
  result = document.getElementById(id).innerHTML
  alert(result)
}
<p id ='myP' onclick="myFunction('myP')"> Hello </p>